0

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

5
  • After your loop finishes, how come your reservedSeats array is empty? Commented Jan 19, 2018 at 2:31
  • That is the mystery I am trying to solve. Maybe I'm doing something wrong or there is some thing wrong with the logic Commented Jan 19, 2018 at 2:37
  • Add a statement printing out seats in the loop. I think you'll be surprised by the output. Commented Jan 19, 2018 at 2:39
  • I edited the code. The print statement does produce 6, 27 but the reservedSeats is still [] Commented Jan 19, 2018 at 2:45
  • There's no print statement in the code you posted. Where are you seeing 6 and 27 being printed? Commented Jan 19, 2018 at 4:26

1 Answer 1

1

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 }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The format of the JSON I receive is exactly as it is in my question. So I need to access the seat_no in another function. I tried your solution but it returns an empty array.
@user1514567 did you find any solution?
is this sample json in your array is complete or partial?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.