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 ...

Get Reactive Programming with Swift 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.