Home > Software engineering >  how to create a loop to find available values until it shows up true
how to create a loop to find available values until it shows up true

Time:04-26

I am working on a timeslot system that will give available time slots and unavailable but I am filtering available slots and loading the array. Sometimes many days don't have available timeslots. I wanted to find the next available slots on recently available days through the loop from the "available" Bool Parameter from the response below (I pasted only part of the response.

    {
  "timeslots" : [
    {
      "slots" : [
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 160,
          "available" : false,
          "timeframe" : "10:00 - 12:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 161,
          "available" : true,
          "timeframe" : "12:00 - 14:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 162,
          "available" : true,
          "timeframe" : "15:00 - 17:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 163,
          "available" : true,
          "timeframe" : "17:00 - 19:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 164,
          "available" : false,
          "timeframe" : "19:00 - 21:00"
        }
      ],
      "day_name" : "tuesday",
      "date" : "2022-04-26",
      "available" : 3,
      "day_abbr" : "26 Apr"
    },
    {
      "slots" : [
        {
          "pk" : 160,
          "day" : "wednesday",
          "timeframe" : "10:00 - 12:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 161,
          "day" : "wednesday",
          "timeframe" : "12:00 - 14:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 162,
          "day" : "wednesday",
          "timeframe" : "15:00 - 17:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 163,
          "day" : "wednesday",
          "timeframe" : "17:00 - 19:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 164,
          "day" : "wednesday",
          "timeframe" : "19:00 - 21:00",
          "selected" : false,
          "available" : false
        }
      ],
      "day_name" : "wednesday",
      "date" : "2022-04-27",
      "available" : 4,
      "day_abbr" : "27 Apr"
    },

I did an iteration like this so far.

   switch response.result {
              case let .success(value):
                  let json = JSON(value)
                  print("Time slot response: \(json)")
                  self.slots.removeAll()
                  self.daySlots.removeAll()
                  self.typeOfSlot = slotType
                  if let slotArray = json[slotType][self.dayIndex ?? 0]["slots"].array{
                      if !slotArray.isEmpty || slotArray != [] {
                          for slotJSON in slotArray {
                              let slot = Slots.parseSlots(slotJSON: slotJSON)
                              self.slots.append(slot)
                          }
                          self.slots = self.slots.filter({ $0.available ?? false })
//
                          if self.slots.count != 0{
                          switch self.typeOfSlot{
                                      case "seasonal_timeslots":
                                      self.seasonalTimeSlotPK = self.slots.first?.pk
                                      print("time slot pk \(self.seasonalTimeSlotPK ?? 0)")
                                          UserDefaults.standard.set(self.seasonalTimeSlotPK, forKey:uds.kSeasonalTimeslotPK)
                              self.selectedSeasonalTimeRange = self.slots.first?.timeFrame
                                          UserDefaults.standard.set(self.selectedSeasonalTimeRange, forKey:uds.kSeasonalTimeRange)

                                      case "timeslots":
                                      self.timeSlotPK = self.slots.first?.pk
                                      print("time slot pk \(self.timeSlotPK ?? 0)")
                                          UserDefaults.standard.set(self.timeSlotPK ?? 0, forKey:uds.kTimeslotPK)
                                      self.selectedTimeRange = self.slots.first?.timeFrame
                                          UserDefaults.standard.set(self.selectedTimeRange ?? "", forKey:uds.kTimeRange)

                                      default:
                                          break
                                      }
                          }
                          
                         // timeframe

                      }
                      else {
                        //  self.tableView.setEmptyView(title: "No available slots found for current date!", message: "Please tap on other days for next available slots.")
                          self.view.makeToast("No Slots Found!", duration: 3.0, position: .bottom)
                      }

Please give me code example for me to search for available slots and stops until it's found.

CodePudding user response:

I'm not really sure what goes om in your code. But you are asking to find the first available slot in your array of slots?

i made some structs to keep track of the data and used Swift 4's Decodable to easier represent the data:

struct Timeslots: Decodable {
    let slots: [Slot]
    
    var firstFreeTime: Slot? {
        slots.first(where: { $0.available })
    }
}

struct Slot: Decodable {
    let day: String
    let selected: Bool
    let pk: Int
    let available: Bool
    let timeFrame: String
}

CodePudding user response:

instead of using the json raw data, you could re-structure your code and use specific models to do what you ask. Here is some example test code to show how to get the slots.

struct Response: Identifiable, Codable {
    let id = UUID()
    var timeslots: [Timeslot]
}

struct Timeslot: Codable {
    let slots: [Slot]
    let dayName: String
    let date: String
    let available: Int
    let dayAbbr: String

    enum CodingKeys: String, CodingKey {
        case slots
        case dayName = "day_name"
        case date, available
        case dayAbbr = "day_abbr"
    }
}

struct Slot: Identifiable, Codable {
    let id = UUID()
    let day: String
    let selected: Bool
    let pk: Int
    let available: Bool
    let timeframe: String
}

struct ContentView: View {
    
    var body: some View {
        Text("testing")
            .onAppear {
                let json = """
    {
  "timeslots" : [
    {
      "slots" : [
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 160,
          "available" : false,
          "timeframe" : "10:00 - 12:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 161,
          "available" : true,
          "timeframe" : "12:00 - 14:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 162,
          "available" : true,
          "timeframe" : "15:00 - 17:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 163,
          "available" : true,
          "timeframe" : "17:00 - 19:00"
        },
        {
          "day" : "tuesday",
          "selected" : false,
          "pk" : 164,
          "available" : false,
          "timeframe" : "19:00 - 21:00"
        }
      ],
      "day_name" : "tuesday",
      "date" : "2022-04-26",
      "available" : 3,
      "day_abbr" : "26 Apr"
    },
    {
      "slots" : [
        {
          "pk" : 160,
          "day" : "wednesday",
          "timeframe" : "10:00 - 12:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 161,
          "day" : "wednesday",
          "timeframe" : "12:00 - 14:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 162,
          "day" : "wednesday",
          "timeframe" : "15:00 - 17:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 163,
          "day" : "wednesday",
          "timeframe" : "17:00 - 19:00",
          "selected" : false,
          "available" : true
        },
        {
          "pk" : 164,
          "day" : "wednesday",
          "timeframe" : "19:00 - 21:00",
          "selected" : false,
          "available" : false
        }
      ],
      "day_name" : "wednesday",
      "date" : "2022-04-27",
      "available" : 4,
      "day_abbr" : "27 Apr"
    }
  ]
}
"""

                let data = json.data(using: .utf8)!
                do {
                    let response = try JSONDecoder().decode(Response.self, from: data)
                   // print("\n--> response: \(response) \n")
                    
                    // here loop over the timeslots
                    for tmslot in response.timeslots {
                        // here loop over the slots
                        for slot in tmslot.slots {
                            if slot.available {
                                print("slot available: \(slot.day)  \(slot.timeframe)")
                            }
                        }
                    }
                    
                } catch {
                    print("error: \(error)")
                }
            }
    }
}
  • Related