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

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.

主站蜘蛛池模板: 青冈县| 永修县| 嵩明县| 安多县| 海盐县| 巫山县| 腾冲县| 永登县| 安平县| 吉首市| 昌都县| 务川| 大兴区| 寿宁县| 海口市| 临高县| 江津市| 夹江县| 娱乐| 临城县| 睢宁县| 彰武县| 平罗县| 西城区| 栾城县| 任丘市| 黄龙县| 衡山县| 新巴尔虎右旗| 普宁市| 长垣县| 隆林| 安乡县| 新和县| 海盐县| 濮阳市| 安塞县| 勐海县| 武川县| 宁津县| 台北市|