“通话中的额外论点”

时间:2019-04-24 02:29:48

标签: swift

从超类调用Enum数据类型后,我的super.init出现错误。我在这里做什么错了?

class Atleta : Pessoa {

    var beltRanking : Int = 1
    let previousGraduation : Date
    var nextGraduation : Date

    init(beltRanking: Int, previousGraduation: Date, nextGraduation: Date) {

        self.beltRanking = 1
        self.previousGraduation = previousGraduation
        self.nextGraduation = nextGraduation

        super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: RolePessoa) {

            self.name = name
            self.country = country
            self.birthDay = birthDay
            self.email = email
            self.joiningDate = joiningDate
            let role = RolePessoa()

        }

    }

另一个文件/类的枚举声明:

enum RolePessoa {
    case Aluno
    case Funcionario
    case Instrutor
    case Visitante
}

这里是Pessoa班:

class Pessoa {

    var bodyStats : BodyStats = BodyStats()
    let name : String
    let country : String
    let birthDay : Date
    let email : String
    let joiningDate : Date
    var role : RolePessoa

    //    var typeOfCar : CarType = .Coupe

    init(name: String, country: String, birthDay: Date, email: String, joiningDate: Date, role: RolePessoa) {

        self.name = name
        self.country = country
        self.birthDay = birthDay
        self.email = email
        self.joiningDate = joiningDate
        self.role = .Aluno

    }

}

1 个答案:

答案 0 :(得分:0)

问题描述

super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: RolePessoa)类中的Atleta方法调用之后,代码中包含方括号。 Swift编译器认为这是作为最后一个参数传递的闭包。

解决方案

这里的目的是调用super.init方法并在那里传递正确的参数。我们可以更改方法调用以实现目标:

super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: .Aluno)

请注意,无论如何,我们都将.Aluno作为角色传递给Pessoa类初始化程序。

重构建议

您可能希望从初始化参数中删除role,以简化代码或为它分配默认值,如下所示:

init(name: String, country: String, birthDay: Date, email: String, joiningDate: Date, role: RolePessoa = .Aluno) {

    self.name = name
    self.country = country
    self.birthDay = birthDay
    self.email = email
    self.joiningDate = joiningDate
    self.role = role
}

然后可以通过以下方式更改超级初始化调用:

super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate)

请注意,在这种情况下,我们根本不指定role,因为默认情况下为它分配了.Aluno。 如果需要,我们还可以指定其他角色:

super.init(name: name, country: country, birthDay: birthDay, email: email, joiningDate: joiningDate, role: .Funcionario)

Initialization对于初学者有很好的有关初始化程序的正式文档。