- Reactive Programming with Swift 4
- Navdeep Singh
- 169字
- 2021-06-24 18:57:58
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"]]
推薦閱讀
- Vue.js 3.x快速入門
- 工程軟件開發(fā)技術(shù)基礎(chǔ)
- JavaScript修煉之道
- Rust編程:入門、實(shí)戰(zhàn)與進(jìn)階
- 算法基礎(chǔ):打開程序設(shè)計(jì)之門
- Learning Neo4j 3.x(Second Edition)
- Scientific Computing with Scala
- Mastering ROS for Robotics Programming
- Python+Tableau數(shù)據(jù)可視化之美
- 打開Go語言之門:入門、實(shí)戰(zhàn)與進(jìn)階
- Apache Camel Developer's Cookbook
- 從零開始學(xué)Android開發(fā)
- Hacking Android
- JavaEE架構(gòu)與程序設(shè)計(jì)
- Java 9:Building Robust Modular Applications