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

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"]]
主站蜘蛛池模板: 临沧市| 平阴县| 土默特左旗| 长岛县| 公主岭市| 湖州市| 丰城市| 祁连县| 内丘县| 明光市| 武邑县| 广东省| 通州区| 龙井市| 成安县| 安福县| 阜城县| 巩留县| 靖宇县| 云霄县| 齐河县| 巴塘县| 濮阳市| 孟州市| 吴江市| 陆良县| 清流县| 桂林市| 宁城县| 汉寿县| 广宗县| 泰兴市| 遂宁市| 喀什市| 谷城县| 临桂县| 墨江| 潢川县| 宁海县| 正蓝旗| 怀化市|