1:根据首字母分组:
let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
输出
let studentsByLetter = ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
2:根据性别分组
var student1 = StudentS()
student1.name = "小明"
student1.sex = Sex.male
student1.age = 18
var student2 = StudentS()
student2.name = "小红"
student2.sex = Sex.female
student2.age = 20
var student3 = StudentS()
student3.name = "小童"
student3.sex = Sex.male
student3.age = 18
var studentss = [student1,student2,student3]
let groups = Dictionary(grouping: studentss) { s in
s.sex
};
let groups = [Sex.male:[student1,student3], Sex.female:[student2]]