美文网首页
swift中Dictionary的grouping by使用

swift中Dictionary的grouping by使用

作者: focusHYD | 来源:发表于2022-02-08 15:14 被阅读0次

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]]

相关文章

网友评论

      本文标题:swift中Dictionary的grouping by使用

      本文链接:https://www.haomeiwen.com/subject/zyvbkrtx.html