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

Convert tuples to Dictionary

With Swift 4, you can now create a new unique Dictionary from an array of tuples consisting of duplicate keys. Let's take an example of an array of tuples with duplicate keys:

let tupleWithDuplicateKeys = [("one", 1), ("one", 2), ("two", 2), ("three", 3), ("four", 4), ("five", 5)]

 Also, you want to convert this array into Dictionary, so you can do this:

let dictionaryWithNonDuplicateKeys = Dictionary(tupleWithDuplicateKeys, uniquingKeysWith: { (first, _) in first })

Now if you try to print dictionaryWithNonDuplicateKeys;

print(dictionaryWithNonDuplicateKeys), the output will be as illustrated:

["three": 3, "four": 4, "five": 5, "one": 1, "two": 2],

This is along with all the duplicate keys removed in the resulting Dictionary.

主站蜘蛛池模板: 樟树市| 平塘县| 潜江市| 镇沅| 米泉市| 延长县| 龙井市| 乌兰察布市| 湖北省| 长汀县| 洞头县| 尖扎县| 浠水县| 尚义县| 元阳县| 普安县| 枣庄市| 沁阳市| 温宿县| 新建县| 林芝县| 湛江市| 金坛市| 福泉市| 军事| 孙吴县| 田林县| 台中市| 龙海市| 包头市| 浙江省| 无棣县| 永胜县| 延长县| 石渠县| 隆回县| 神池县| 武义县| 启东市| 南召县| 金溪县|