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

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.
主站蜘蛛池模板: 和平区| 江城| 云林县| 仙游县| 邵阳市| 林州市| 桃园市| 治多县| 韩城市| 汤阴县| 阳春市| 南京市| 寿光市| 崇州市| 库尔勒市| 崇礼县| 洛南县| 兴国县| 南靖县| 株洲县| 长沙县| 古蔺县| 县级市| 砀山县| 玉门市| 沂南县| 龙岩市| 阳城县| 汉川市| 康马县| 昌乐县| 项城市| 朔州市| 开封市| 芦山县| 措美县| 福安市| 彭山县| 石门县| 巢湖市| 手游|