Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Array to Dictionary?

I have a large array and need to access it by a key (a lookup) so I need to create Dictionary. Is there a built in function in Swift 3.0 to do so, or do I need to write it myself?

First I will need it for a class with key "String" and later on maybe I will be able to write a template version for general purpose (all types of data and key).


Note for 2019. This is now simply built-in to Swift 5, uniqueKeysWithValues and similar calls.

like image 274
Peter71 Avatar asked Sep 30 '16 12:09

Peter71


1 Answers

Is that it (in Swift 4)?

let dict = Dictionary(uniqueKeysWithValues: array.map{ ($0.key, $0) }) 

Note: As mentioned in the comment, using uniqueKeysWithValues would give a fatal error (Fatal error: Duplicate values for key: 'your_key':) if you have duplicated keys.

If you fear that may be your case, then you can use init(_:uniquingKeysWith:) e.g.

let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)] let firstValues = Dictionary(pairsWithDuplicateKeys, uniquingKeysWith: { (first, _) in first }) let lastValues = Dictionary(pairsWithDuplicateKeys, uniquingKeysWith: { (_, last) in last }) print(firstValues)  //prints ["a": 1, "b": 2]  print(lastValues)  //prints ["a": 3, "b": 4] 
like image 119
Kamil Nomtek.com Avatar answered Sep 23 '22 05:09

Kamil Nomtek.com