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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With