官术网_书友最值得收藏!

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 putting in a word. The preceding code besides the shorthand +, uses zip to fix duplicate keys by adding the two contrasting values.

zip(_:_:) creates a sequence of pairs built out of two underlying sequences.
主站蜘蛛池模板: 咸阳市| 怀远县| 合肥市| 汝城县| 万安县| 清水河县| 禄劝| 余江县| 温宿县| 寿宁县| 保山市| 乌拉特中旗| 武强县| 荣成市| 金昌市| 阜新市| 工布江达县| 新巴尔虎右旗| 来凤县| 陕西省| 三河市| 辽宁省| 盘锦市| 枣强县| 无极县| 盘山县| 英吉沙县| 都安| 轮台县| 尼勒克县| 象州县| 海兴县| 平南县| 夏津县| 清河县| 融水| 南陵县| 积石山| 马山县| 乌拉特前旗| 丽江市|