简体   繁体   中英

Retrieve JSON Object and populate array Swift

I have a json object of this structure:

[
    {
        "id": 1,
        "seat_no": 6
    },
    {
        "id": 2,
        "seat_no": 27
    }
]

The main challenge is that I need to get the seat_no and add that to an int array which I will be using later on:

func getReserved() -> [Int] {
  var reservedSeatsJSON : JSON = JSON()
  var seats = Int()
  var reservedSeats = [Int]()

  for item in reservedSeatsJSON.array! {
     seats = item["seat_no"].int!
     reservedSeats.append(seats)
     self.reservedSeatsLabel.text = "Reserved(\(reservedSeatsJSON.array!.count))"
  }
  return reservedSeats      
}              

Each time I run this, the reservedSeats returns empty. The main idea here is that I need to populate an int array in a for loop and return the populated array outside the for loop

First check is reservedSeatsJSON json contains actual JSON?

if it contains actual JSON then do as like below. short and simple way.

func getReserved() -> [Int] {
     var reservedSeatsJSON : JSON = JSON()
     self.reservedSeatsLabel.text = "Reserved(\(reservedSeatsJSON.array.count))" 

     return reservedSeatsJSON.arrayValue.map { $0["seat_no"].intValue }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM