cannyboy cannyboy - 1 month ago 7
Swift Question

Object from Array of Dictionaries into an Array

If I have an array of dictionaries in my NSUserDefaults:

["name":"John", "birthplace":"New York"]
["name":"Eric", "birthplace":"London"]
["name":"Sven", "birthplace":"Stockholm"]
["name":"Pierre", "birthplace":"Paris"]


What is the simplest way to get all the names into an array like this

John, Eric, Sven , Pierre

Answer

First off, you should get the array from user defaults in correct type which is [[String: String]]:

let defaults = NSUserDefaults.standardUserDefaults()
if let peopleArray = defaults.arrayForKey("people") as? [[String: String]] {
  ...
}

Then you can use flatMap (or map if you are sure each dictionary has the key name) to extract the names:

peopleArray.flatMap { $0["name"] }