To są moje dane JSON:

let jsonArray = [
    "array": [12.34, 56.78],
    "users": [
        [
            "id": 987654,
            "info": [
                "name": "jack",
                "email": "jack@gmail.com"
            ],
            "feeds": [98, 23443, 213239, 23232]
        ],
        [
            "id": 654321,
            "info": [
                "name": "jeffgukang",
                "email": "jeffgukang@gmail.com"
            ],
            "feeds": [12345, 56789, 12423, 12412]
        ]
    ]
]

Mój kod do odczytu "Użytkownicy" i "ID"

let idArr = NSMutableArray()
let infoArr = NSMutableArray()
let usersArr = NSMutableArray()

for index in 0...1 { 
    infoArr.addObjects(from: (jsonArray["users"]![index] as! [String: Any])["info"] as! [Any]) 
} 
print("info arr : (infoArr)") 
for index in 0...1 { 
    idArr.addObjects(from: (jsonArray["users"]![index] as! [String: Any])["id"] as! [Any]) 
} 
print("id arr : (idArr)")

Ale robię błędy takie jak:

Nie można rzucić wartości typu "Swift._swiftdeferRedNsdictionary " (0x1079B8420) do "Nsarray" (0x106332008)

Nie można było rzucać wartości typu "Swift.dictionary " (0x1105AC550) do "Swift.array " (0x1105ABF30).

Nie można było rzucać wartości typu "Swift.int" (0x11149F8C0) do "Swift.array " (0x1114C4F30).

-2
iOS 5 czerwiec 2018, 14:11

3 odpowiedzi

Najlepsza odpowiedź

Spróbuj tego:

var infoArr: [Any] = []
var idArr: [Any] = []

for i in 0..<(jsonArray["users"]!).count {
  infoArr.append((jsonArray["users"]![i] as! [String: Any])["info"])
  idArr.append((jsonArray["users"]![i] as! [String: Any])["id"])
}
-1
Anshul Bhatheja 5 czerwiec 2018, 11:21
**Check correct code**


  var idArr = [Int]()
    var infoArr = [[String:Any]]()
    let usersArr = [Any]()

    for index in 0...1 {
        infoArr.append((jsonArray["users"]![index] as! [String: Any])["info"] as! [String:Any])
    }
    print("info arr : \(infoArr)")
    for index in 0...1 {
        idArr.append((jsonArray["users"]![index] as! [String: Any])["id"] as! Int)
    }
    print("id arr : \(idArr)")
0
Vishal Patel 5 czerwiec 2018, 11:38

1- Zmień to

["info"] as! [Any]

Do

["info"] as! [String:Any]

2- I to

["id"] as! [Any]

Do

["id"] as! NSNumber

//

var idArr = [NSNumber]()
var infoArr = [[String:Any]]()

for index in 0...1 { 
 infoArr.append((jsonArray["users"]![index] as! [String: Any])["info"] as! [String:Any]) 
} 
print("info arr : (infoArr)") 
for index in 0...1 { 
idArr.append((jsonArray["users"]![index] as! [String: Any])["id"] as! NSNumber) 
} 
0
Sh_Khan 5 czerwiec 2018, 11:41