user3805066 user3805066 - 3 years ago 163
iOS Question

return array of json in swift

i have elementary problem in swift,
this is my json :

{
1: 2,
2: 27,
3: 43,
4: 0,
5: 0,
6: 0,
7: 24,
8: 22,
9: 11,
10: 0,
11: 0,
12: 0,
13: 7,
14: 0,
15: 0,
16: 0,
17: 0,
18: 0,
19: 0,
20: 0,
}


i want set this value in my array by below code but it not work:

let jsonData = try? JSONSerialization.jsonObject(with: data, options: [])
guard let jsonval = jsonData as? [String:AnyObject] else { return }

var num = [Int]()

for i in 1 ..< 20 {

num[i] = jsonval[i] as! Int

}


what is solution???
thanks

Answer Source

After changing the Json to this format:

{"1":2,"2":27,...}

Change the loop to:

    for i in 1 ... 20 {
        if let value = jsonval["\(i)"] as? Int {
            num.append(value)
            print(value)
        }
    }

Then you will have the array with elements from Json, and print them by the way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download