gpt4 book ai didi

ios - Swift:init中super.init和self.attribute的顺序

转载 作者:行者123 更新时间:2023-11-28 07:16:58 25 4
gpt4 key购买 nike

我正在尝试像下面这样初始化一个子类:

class NameShape{
var numberOfSide: Int = 0
var name:String
func simpleDescription() -> String {
return "A square with \(numberOfSide) sides."
}
init (name: String){
self.name = name
}
}

class Square:NameShape{
var sideLength: Double
init(name: String, sideLength: Double){
super.init(name: name)
self.sideLength = sideLength
numberOfSide = 4
}

func area() ->Double {
return sideLength * sideLength
}

override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}

}

我得到一个错误 property 'self.sideLength' not initialized at super.init call,所以我切换 self.sideLength = sideLengthsuper.init (name:姓名),如:

class Square:NameShape{
var sideLength: Double
init(name: String, sideLength: Double){
self.sideLength = sideLength
super.init(name: name)
numberOfSide = 4
}

func area() ->Double {
return sideLength * sideLength
}

override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}

}

现在好了,谁能解释一下背后的原理?谢谢!!!

最佳答案

之所以更改它是因为 Apple 对这种语言的“安全”方法。任何在方法调用之前未初始化的非包装和非初始化变量都将引发编译器错误。这是 Swift 中的一项安全功能。基本上,编译器试图避免你做这样的事情:

init(name: String, sideLength: Double){            
super.init(name: name)
someFunctionThatUsesSideLengthBeforeItsInitialized(sideLength)
self.sideLength = sideLength
numberOfSide = 4
}

此方法 someFunctionThatUsesSideLengthBeforeItsInitialized 可能会导致异常。在我看来,像 super.init 这样的父类(super class)函数应该不受这条规则的约束。

关于ios - Swift:init中super.init和self.attribute的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com