Resolving duplicates

Swift 4 allows us to initialize a Dictionary from a sequence with duple existence of entries and manage the duplicates easily. Suppose you have an array of friends as follows:

var friends = ["Deapak", "Alex", "Ravi", "Deapak"]

Also suppose that you want to create a Dictionary with all the friends, remove duplicates, and just maintain the count of the number of occurrences that occurred in the initial friends array; you can do this by initiating a new Dictionary, as follows:

let friendsWithMultipleEntries = Dictionary(zip(friends, repeatElement(1, count: friends.count)), uniquingKeysWith: +)

The output will be the following:

["Deapak": 2, "Ravi": 1, "Alex": 1], 

This helps you avoid overwriting key-value pairs, without ...

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.