swift中Dictionary的grouping by使用

2022-02-08  本文已影响0人  focusHYD

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]]
上一篇 下一篇

猜你喜欢

热点阅读