Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`

As of Swift 4 you can create a dictionary directly from a
sequence of key/value pairs:

let keys = ["one", "two", "three"]
let values = [1, 2, 3]

let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))

print(dict) // ["one": 1, "three": 3, "two": 2]

This assumes that all keys are different, otherwise it will abort
with a runtime exception.

If the keys are not guaranteed to be distinct then you can do

let keys = ["one", "two", "one"]
let values = [1, 2, 3]

let dict = Dictionary(zip(keys, values), uniquingKeysWith: { $1 })

print(dict) // ["one": 3, "two": 2]

The second argument is a closure which determines which value “wins”
in the case of duplicate keys.

Leave a Comment