Fabrizio Prosperi
Fabrizio Prosperi

Reputation: 1398

Looping an array of NSDictionaries in swift

Ok, trying to catch the last train to learn Swift, I have seen similar questions but I am not getting them to solve my issue.

I have an NSDictionary called entries, and one of the values, corresponding to key "TYPES" is an NSArray of NSDictionaries. I am trying to loop over this latter NSDictionary and retrieve an integer value for the key "TID", I am doing:

for dict in entries["TYPES"] as NSDictionary {
   let tid : Int = typeDict["TID"]
}

But I am receiving as error: (key: AnyObject, value: AnyObject) does not have a member named 'subscript'

I understand this is due to entries["TYPES"] being anyObject! and comes from Xcode 6 beta 6, where a large number of Foundation APIs have been audited for optional conformance and hence need unwrapping but I have tried my best to unwrap without success, the compiler is always complaining a different thing. Someone knows how to do this?

Upvotes: 1

Views: 11637

Answers (1)

Antonio
Antonio

Reputation: 72760

If this is a sample of your dictionary:

var entries: NSDictionary = [
    "TYPES": [
        [],
        ["TPD": 2],
        ["TID": 4]
    ] as NSArray
]

you have to:

  • retrieve the element identified by the TYPES key, and attempt to cast as NSArray
  • loop through all elements of the array
  • attempt a cast of each element as NSDictionary
  • check for the TID key existence, and read its value
  • if the value is not nil, the search is over

This is the code:

var tid: Int?
if let types = entries["TYPES"] as? NSArray {
    for type in types {
        if let dict = types.lastObject as? NSDictionary {
            tid = dict["TID"] as? Int
            if tid != nil {
                break
            }
        }
    }
}

Running the code in a playground with the sample data, the output I see is {Some 4}.

However I would keep @Zaph's advice into account and model your data in a different way, using structs and/or classes

Upvotes: 9

Related Questions