Accessing values from Dictionaries that are part of an Array in Swift


I'm trying to use a for loop to access the values for the same key within an array of dictionaries in Swift.

For example,

let dictionaryOne = [ "name": "Peter", "age": "42", "location": "Milwaukee"] let dictionaryTwo = [ "name": "Paul", "age": "89", "location": "Denver"] let arrayOfDictionaries = [dictionaryOne, dictionaryTwo]

I'm attempting to create a function using a for loop that will output an array containing the values for location i.e. ["Milwaukee", "Denver"]

I have looked at other responses but I can only find how to access the value for "location" straight from the dictionary itself, which would be cumbersome if there were many different dictionaries rather than just two.

Many thanks for any help you can provide!

-------------Problems Reply------------

The way I see it, you would populate a new array of Strings from the cities listed before.

var locations = [String]()

for dictionary in arrayOfDictionaries{


You can take advantage of the map method, whose purpose is to loop through the array and transform each element into another type: { (dict: [String : String]) -> String? in
return dict["location"]

The closure passed to the map receives an array element, and returns the transformed value - in your case, it retrieves and returns the value for the location key.

You can also use the compact form: { $0["location"] }

Note that this method returns an array of optional strings, because the dictionary subscript operator always returns an optional. If you need an array of non optionals, then this is the unsafe version:

let x = { $0["location"]! }

Of course if the value for "location" key doesn't exist for an array element, a runtime exception will be raised.

More info about map at the Swift Standard Template Library

There are a few ways you could do this. One is to use key-value coding (KVC):

let locations = (arrayOfDictionaries as NSArray).valueForKey("location") as [String]

Category:arrays Views:0 Time:2014-09-30

Related post

Copyright (C), All Rights Reserved.

processed in 0.117 (s). 11 q(s)