分组功能时如何消除错误?

时间:2018-09-21 20:07:53

标签: ios swift

我的问题是分组功能对我不起作用。 我所做的是:

import UIKit

struct Person
{
    let firstname : String

    let lastname : String

    let age : Int
}

class GroupingViewController: UIViewController {

    let people = [
                  Person(firstname: "Mabuto", lastname: "Cohen", age: 20),

                  Person(firstname: "Nagasta", lastname: "Bagamba", age: 21),

                  Person(firstname: "Embazala", lastname: "Levi", age: 22),

                  Person(firstname: "Musasabha", lastname: "Israel", age: 23),

                  Person(firstname: "Bambusto", lastname: "Yaakov", age: 24),

                  Person(firstname: "Zeus", lastname: "Jupiter", age: 25),

                  Person(firstname: "Berry", lastname: "Tzakala", age: 26),

                  Person(firstname: "Uzi", lastname: "Yenmale", age: 27),

                  Person(firstname: "Yudokulis", lastname: "Lifshi", age: 28),

                  Person(firstname: "Adolf", lastname: "Hitler", age: 29),

                  Person(firstname: "Johnny", lastname: "Jenkins", age: 30),

                  Person(firstname: "John", lastname: "Doe", age: 31),

                  Person(firstname: "Andrey", lastname: "Homo", age: 33),

                  Person(firstname: "Rupert", lastname: "Pupkin", age: 32),

                  Person(firstname: "Bentzi", lastname: "Navad", age: 34),

                  Person(firstname: "Shlukh", lastname: "Batahat", age: 35),

                  Person(firstname: "Motako", lastname: "Nambuto", age: 36),

                  Person(firstname: "Abahabusto", lastname: "Menashe", age: 37),

                  Person(firstname: "Benny", lastname: "Moos", age: 38),

                  Person(firstname: "Alex", lastname: "Tarzan", age: 39)

                  ]

    // how do we perform the grouping ? dictionaries ?

    let groupedDictionary = Dictionary(grouping: people, by: {$0["age"]!})


    var groupedPeople = [[Person]]()

    var keys = groupedDictionary.keys.sorted()

    keys.forEach {(key) in

    groupedPeople.append(groupedDictionary[key]!)

    }

    groupedPeople.forEach({

    $0.forEach({print($0)})

    })

我有2个类似的错误:


let groupedDictionary = Dictionary(grouping: people, by: {$0["age"]!}),我得到

  

错误:“无法在属性内使用实例成员'people'   初始化器属性初始值设定项在“自我”可用之前运行”

keys.forEach {(key) in

    groupedPeople.append(groupedDictionary[key]!)

    }

我明白了

  

错误的“已声明的声明”

如何解决?

0 个答案:

没有答案