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

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.
主站蜘蛛池模板: 孟州市| 咸丰县| 启东市| 宣城市| 华宁县| 德令哈市| 色达县| 金乡县| 桂平市| 马山县| 邹平县| 句容市| 交口县| 都安| 南江县| 余姚市| 油尖旺区| 晴隆县| 红河县| 佳木斯市| 和田县| 小金县| 新营市| 邹平县| 双柏县| 曲松县| 象山县| 泰兴市| 福建省| 长沙市| 旺苍县| 新绛县| 鹤壁市| 夹江县| 曲松县| 台南县| 天峻县| 缙云县| 辽宁省| 周口市| 舞阳县|