Search code examples
iosarraysswiftdictionaryfor-in-loop

Cycling element in array of dictionary


I have this code:

let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                for element in jsonResults {
                    for (chiave,valore) in element {
                        print("la chiave\(chiave) è uguale a \(valore)")
                    }
                }

I have an erro in this row:

for (chiave,valore) in element {

Type element Aka AnyObject does not conform to protocol 'Sequence Type'

jsonResults is an Array

and

element is an Dictionary

Can I cast element as a Dictionary?

Array is similar to this:

[0] : 92 elements
    ▿ [0] : 2 elements
      - .0 : NOME
      - .1 : MARIO
    ▿ [1] : 2 elements
      - .0 : CAP_DOMICILIO
      - .1 : 000000
    ▿ [2] : 2 elements
      - .0 : DATA_ULTIMO_AGG
      - .1 : 2015-09-22 

Solution

  • I would cast Element to [String:AnyObject]

    Something like

                if let jsonResults = jsonResults as? [[String: AnyObject]] {
                    for element in jsonResults {
                        //Do stuff
                    }
                }