【问题标题】:Convenience initialiser keeps crashing however designated initialiser works fine?便利初始化程序不断崩溃,但指定的初始化程序工作正常?
【发布时间】:2019-08-20 08:35:24
【问题描述】:

当使用便捷初始化程序创建实例时,操场一直给我这个错误“错误:执行被中断,原因:EXC_BAD_ACCESS (code=2, address=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)

【问题讨论】:

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


    【解决方案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 是多余的。

    【讨论】:

    • 感谢您的解释!我还是 Swift 的新手,这真的很有帮助,有没有一种方便的 init 方法可以使用指定的初始化程序默认值?而不是像上面描述的那样提供默认值
    • 除了arsenal,没有默认值。必须在声明行中指定默认值。
    • ?‍♂️ 再次感谢!我知道我哪里出错了
    • 并且请遵守结构和类名以大写字母开头的命名约定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多