How do I create dictionary from array of tuples? How do I create dictionary from array of tuples? ios ios

How do I create dictionary from array of tuples?


Swift 4

If your tuples is (Hashable, String) you can use:

let array = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")]let dictionary = array.reduce(into: [:]) { $0[$1.0] = $1.1 }print(dictionary) // ["key1": "value1", "key2": "value2", "key3": "value3"]


Swift 4

For creation you can use native Dictionary's init functions:

Dictionary(uniqueKeysWithValues: [("a", 0), ("b", 1)]) // ["b": 1, "a": 0]Dictionary(uniqueKeysWithValues: [("a", 0), ("b", 1), ("b", 2)])// Fatal error: Duplicate values for key: 'b'// takes the first matchDictionary([("a", 0), ("b", 1), ("a", 2)], uniquingKeysWith: { old, _ in old })// ["b": 1, "a": 0]// takes the latest matchDictionary([("a", 0), ("b", 1), ("a", 2)], uniquingKeysWith: { $1 }) // ["b": 1, "a": 2]

Also if you want to have the shortcut:

Dictionary([("a", 0), ("b", 1), ("a", 2)]) { $1 } // ["b": 1, "a": 2]


Depending on what you want to do, you could:

let tuples = [(0, "0"), (1, "1"), (1, "2")]var dictionary = [Int: String]()

Option 1: replace existing keys

tuples.forEach {    dictionary[$0.0] = $0.1}    print(dictionary) //prints [0: "0", 1: "2"]

Option 2: Don't allow repeting keys

enum Errors: Error {    case DuplicatedKeyError}do {    try tuples.forEach {        guard dictionary.updateValue($0.1, forKey:$0.0) == nil else { throw Errors.DuplicatedKeyError }    }    print(dictionary)} catch {    print("Error") // prints Error}


matomo