便利初始化程序不断崩溃,但是指定的初始化程序工作正常吗?

时间:2019-03-29 11:48:02

标签: swift initialization init swift-playground convenience-methods

在使用便捷初始化程序创建实例时,游乐场不断向我显示以下错误:“错误:执行被中断,原因:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee5ae9ff8)”,但是在使用指定的初始化程序时,它可以正常工作。

我不确定我是否正确设置了便捷初始化程序,以便在创建新实例时仅需要使用arsenal参数。

class FootballTeams {

 var liverpool: String
 var chelsea: String
 var manchesterunited: String
 var arsenal: String = "fourth"

 init(arsenal:String, chelsea:String,     
      liverpool: String, manchesterunited:String ) { //designated initialiser
    self.arsenal = arsenal
    self.chelsea = chelsea
    self.liverpool = liverpool
    self.manchesterunited = manchesterunited
}

 convenience init(arsenal: String){
    self.init(arsenal: arsenal) //call to designated initialiser   above
    self.arsenal = arsenal
}
}

let properInstance = FootballTeams(arsenal: "Overides stored  property value", chelsea: "a", liverpool: "b", manchesterunited: "b")
print(properInstance.arsenal)

let convenienceInstance = FootballTeams(arsenal: "This is an instance from the convenience init")
print(convenienceInstance.arsenal)

1 个答案:

答案 0 :(得分:1)

您正在陷入无限循环,没有看到警告

  

通过此函数的所有路径都将自行调用

这意味着init(arsenal呼叫init(arsenal呼叫init(arsenal呼叫init(arsenal呼叫init(arsenal……

要调用便捷初始化程序,您必须调用指定的初始化程序并提供默认值

convenience init(arsenal: String) {
    self.init(arsenal: arsenal, chelsea:"sixth", liverpool: "first", manchesterunited: "fifth") //call to designated initialiser   above
}

多余的行self.arsenal = arsenal是多余的。