- Reactive Programming with Swift 4
- Navdeep Singh
- 114字
- 2025-04-04 17:21:12
Convert tuples to Dictionary
With Swift 4, you can now create a new unique Dictionary from an array of tuples consisting of duplicate keys. Let's take an example of an array of tuples with duplicate keys:
let tupleWithDuplicateKeys = [("one", 1), ("one", 2), ("two", 2), ("three", 3), ("four", 4), ("five", 5)]
Also, you want to convert this array into Dictionary, so you can do this:
let dictionaryWithNonDuplicateKeys = Dictionary(tupleWithDuplicateKeys, uniquingKeysWith: { (first, _) in first })
Now if you try to print dictionaryWithNonDuplicateKeys;
print(dictionaryWithNonDuplicateKeys), the output will be as illustrated:
["three": 3, "four": 4, "five": 5, "one": 1, "two": 2],
This is along with all the duplicate keys removed in the resulting Dictionary.