简体   繁体   中英

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

G'day,

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 ie ["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!

You can take advantage of the map method, whose purpose is to loop through the array and transform each element into another type:

arrayOfDictionaries.map { (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:

arrayOfDictionaries.map { $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 = arrayOfDictionaries.map { $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]

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{
    locations.append(dictionary["location"]!)
}

println(locations)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM