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

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"]]
主站蜘蛛池模板: 荔浦县| 卢湾区| 临泽县| 斗六市| 衢州市| 黔南| 崇仁县| 高陵县| 沽源县| 商河县| 疏附县| 香河县| 兴文县| 克拉玛依市| 简阳市| 石家庄市| 兴化市| 南和县| 金沙县| 邯郸县| 浮山县| 定结县| 凌海市| 乳山市| 蕉岭县| 延寿县| 合江县| 多伦县| 巧家县| 鹰潭市| 鄂托克旗| 阿克陶县| 大新县| 马公市| 莆田市| 莱州市| 彭州市| 磴口县| 惠来县| 噶尔县| 永和县|