1

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

1 Answer 1

3

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"] }
Sign up to request clarification or add additional context in comments.

3 Comments

updated question. how would I get this array out of NSUserDefaults?
yes, they are saved with something like defaults.setObject([["name":"John", "birthplace":"New York"],["name":"Eric", "birthplace":"London"]], forKey: "people")
If I do var peopleArray = defaults.arrayForKey("people") then the flatMap code produces Cannot subscript a value of type '[AnyObject]' with an index of type 'String' (Swift 2.x)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.