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

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.

主站蜘蛛池模板: 德保县| 蒙自县| 当雄县| 东丰县| 米林县| 五莲县| 阿城市| 保山市| 英超| 滨州市| 阿鲁科尔沁旗| 海兴县| 张家界市| 盐山县| 梅河口市| 休宁县| 毕节市| 东乌| 玛曲县| 清水河县| 滦南县| 秀山| 沽源县| 城市| 酉阳| 宝兴县| 南投县| 宜良县| 黄山市| 保定市| 惠东县| 泸西县| 乌拉特中旗| 静安区| 西安市| 中山市| 香河县| 鄄城县| 陕西省| 呼和浩特市| 九寨沟县|