Getting Values out of an Array of Dictionaries

I have an array of dictionaries and need to filter what gets returned by the value of key, but I am not sure how to accomplish that. Any help here would be appreciated.


Thanks

Ben

var arrayOfDict = NSMutableArray()
var dict = ["Name": "Jim", "Writes": "Left"]
var dict2 = ["Name":"Jon", "Writes": "Right"]
arrayOfDict.addObject(dict)
arrayOfDict.addObject(dict2)
arrayOfDict.count
for test in arrayOfDict {
    for (key,value) in test as! NSDictionary {
        if(key as! String == "Name"){
            if(value as! String == "Jon"){
                print("Found Jon")
                // Found Jon How do I get the value of his
                // Writes Key?
            }
           
        }
    }
}
Answered by tdeleon in 121486022
let dict = ["Name": "Jim", "Writes": "Left"]
let dict2 = ["Name":"Jon", "Writes": "Right"]
let arrayOfDict = [dict, dict2]
let jon = arrayOfDict.filter {
    $0["Name"] == "Jon"
}
if let first = jon.first {
    let writes = first["Writes"]
}


The filter method will check for any dictionary whose Name key is Jon, returning an array of those that match. If you only care about the first match, you can use first as shown.


If using Swift, there's usually no need to use NSDictionary. If you need to interact with something like NSJSONSerialization, you can still make your Swift dictionary [NSObject: AnyObject] instead.

test["Writes"]

Accepted Answer
let dict = ["Name": "Jim", "Writes": "Left"]
let dict2 = ["Name":"Jon", "Writes": "Right"]
let arrayOfDict = [dict, dict2]
let jon = arrayOfDict.filter {
    $0["Name"] == "Jon"
}
if let first = jon.first {
    let writes = first["Writes"]
}


The filter method will check for any dictionary whose Name key is Jon, returning an array of those that match. If you only care about the first match, you can use first as shown.


If using Swift, there's usually no need to use NSDictionary. If you need to interact with something like NSJSONSerialization, you can still make your Swift dictionary [NSObject: AnyObject] instead.

Getting Values out of an Array of Dictionaries
 
 
Q