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

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.
主站蜘蛛池模板: 荥经县| 隆回县| 汽车| 吉木乃县| 嘉黎县| 蒙自县| 浏阳市| 四子王旗| 嘉黎县| 浑源县| 麻城市| 天津市| 南华县| 邵武市| 凭祥市| 安龙县| 滦平县| 都昌县| 九江县| 慈利县| 庄浪县| 五峰| 瓦房店市| 介休市| 呼和浩特市| 顺平县| 微博| 周至县| 扶风县| 崇左市| 通城县| 林周县| 余江县| 缙云县| 出国| 永昌县| 周口市| 高安市| 天津市| 宜都市| 平舆县|