Swift JSON Could not cast value of type '__NSArrayM' to 'NSDictionary'

hI,


I'm getting JSON from a web service in the following format:


{"wards":[{"ward":[{"id":"1", "name":"Ward A"},{"id":"2", "name":"Ward B"},{"ID":"3", "name":"Ward C"}]}]}



When i'm trying to assing it to my custom object:

class Ward {
    var id:Int
    var name:String
    init(id:Int, name:String){
    self.id = id
    self.name = name}
}


I'm getting the following error on line 03 \: Could not cast value of type '__NSArrayM' (0x10e710b60) to 'NSDictionary' (0x10e710fe8).

func loadWards(wards:NSArray){
        for ward in wards{
            let ward2 = ward["ward"]! as! NSDictionary
            let id  = Int(ward2["id"]! as! String)!
        let name  = ward2["name"]! as! String
           
        let wardObj = Ward(id: id, name: name)
            wardsCollection.append(wardObj)
            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()
            }
        }
    }



Is there something i'm doing incorrect with assigning the values?


Thanks

ward["ward"] is in fact an array of dictionaries:


{"wards":[{"ward":[ …

Thanks for your reply.


Is there any way around this error?


I've tried something like:

let id = Int(ward["ward"]!["id"]! as! String)!


but this doesnot work either.

Your "wards" array is an array of one thing: a dictionary with one object keyed to "ward".


So, ward["ward"] is that one object, and it's an array.


So, you need to cast ward["ward"] to an array, and loop over the objects it contains, which are the dictionaries you really want.


Your code will look like this:


func loadWards(wards:NSArray){ 
     for ward in wards{ 
          let wardArray = ward["ward"]! as! NSArray
          for ward2 in wardArray {
               let id  = Int(ward2["id"]! as! String)! 
               let name  = ward2["name"]! as! String 
            
               let wardObj = …
Swift JSON Could not cast value of type '__NSArrayM' to 'NSDictionary'
 
 
Q