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

标签 swift initialization init swift-playground convenience-methods

当使用便利初始化程序创建实例时, Playground 不断给我这个错误“错误:执行被中断,原因:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee5ae9ff8)”但是当使用指定的初始化程序时它工作正常。 p>

我不完全确定我是否正确设置了便利初始化程序,以便在创建新实例时只需要 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)

最佳答案

您遇到了无限循环,您没有看到警告吗

All paths through this function will call itself

这意味着 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是多余的。

关于swift - 便利初始化程序不断崩溃,但指定的初始化程序工作正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55416807/

相关文章:

c - 为什么我得到 : "error: assignment to expression with array type"

objective-c - 如果我多次调用 nsobject init 会发生什么?它会增加保留计数吗?

ios - 警报 "Sign in to iTunes Store"和 "Battery low"暂停我的应用程序堵塞。我怎样才能取消暂停它们?

swift - stringByReplacingOccurrencesOfString 删除整个字符串

ios - Firebase 通知(仅数据)未在前台接收

swift - self.name = Swift 中的名称。我不明白为什么需要这些代码

objective-c - Objective-C 中的对象初始化顺序

swift - 为什么我不能在 switch 语句中使用元组常量作为 case

ios - 如何在 iOS UITableViewController 中初始化一个属性

c++ - 为什么我不能访问这个类的成员?