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

Grouping initializer

Grouping initializer is the new addition to the Dictionary that converts a sequence into a Dictionary of sequences grouped as per your ambition. Continuing our people example, we can use people.keys to get back an array of people names and then group them by their first letter, like this:

let groupedPeople = Dictionary(grouping: people.keys) { $0.prefix(1) }
print(groupedPeople)

This will output the following:

["T": ["Tom"], "A": ["Alex"], "R": ["Rex", “Ravi”]]

Here, T, A, and R are initializers to the distinct names. For instance, consider that you had one more name in the Dictionary, say "Adam" aged 55:

["Tom": 24, "Alex": 23, "Rex": 21, "Ravi": 43, "Adam": 55]

In this case, the groupedPeople array might look something like this:

["T": ["Tom"], "A": ["Alex", "Adam"], "R": ["Rex", “Ravi”]]

Alternatively, we can group people based on the length of their names, as shown:

let groupedPeople = Dictionary(grouping: people.keys) { $0.count }
print(groupedPeople)

This will output the following:

[3: ["Tom","Rex"], 4: ["Alex", "Ravi","Adam"]]
主站蜘蛛池模板: 马鞍山市| 星座| 万荣县| 清水河县| 乌拉特前旗| 化州市| 玉门市| 东山县| 河津市| 顺昌县| 鲁山县| 东源县| 崇信县| 同德县| 弥渡县| 林甸县| 龙里县| 新安县| 隆林| 江阴市| 东乌珠穆沁旗| 平顺县| 德阳市| 金山区| 阜宁县| 红安县| 沙湾县| 大安市| 永胜县| 陆川县| 龙泉市| 呈贡县| 沅江市| 曲麻莱县| 朔州市| 满洲里市| 东源县| 玛沁县| 绥阳县| 长寿区| 庄浪县|