gpt4 book ai didi

properties - Swift 类 : Property not initialized at super. init 调用中出现错误

转载 作者:行者123 更新时间:2023-11-30 12:13:20 27 4
gpt4 key购买 nike

我有两个类,ShapeSquare

class Shape {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}

class Square: Shape {
var sideLength: Double

init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}

通过上面的实现,我收到错误:

property 'self.sideLength' not initialized at super.init call
super.init(name:name)

为什么我必须在调用 super.init 之前设置 self.sideLength

最佳答案

引用《Swift 编程语言》,它回答了您的问题:

“Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:”

Safety check 1 “A designated initializer must ensure that all of the “properties introduced by its class are initialized before it delegates up to a superclass initializer.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

关于properties - Swift 类 : Property not initialized at super. init 调用中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762552/

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