便利初始化器不断崩溃,但指定初始化器工作正常?
Convenience initialiser keeps crashing however designated initialiser works fine?
当使用便利初始化器创建实例时,playground 一直给我这个错误 "error: Execution was interrupted, reason: 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)
你运行进入了一个无限循环,你没看到警告吗
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
是多余的。
当使用便利初始化器创建实例时,playground 一直给我这个错误 "error: Execution was interrupted, reason: 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)
你运行进入了一个无限循环,你没看到警告吗
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
是多余的。