Swift类中的错误:属性未在super.init调用时初始化 [英] Error in Swift class: Property not initialized at super.init call
问题描述
我有两个类, Shape
和 Square
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
}
}
上面的实现我得到错误:
With the implementation above I get the error:
property 'self.sideLength' not initialized at super.init call
super.init(name:name)
为什么我必须设置 self。在调用
super.init
之前
推荐答案
p> Swift编程语言的报价,它回答了你的问题:
Quote from The Swift Programming Language, which answers your question:
Swift的编译器执行四个有用的安全检查, $ b两阶段初始化完成没有错误:
"Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:"
安全检查1指定的初始化程序必须确保其引入的所有
属性类在初始化之前
委托给一个超类初始化器。
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."
摘录:Apple Inc.Swift编程语言iBooks。
https://itunes.apple.com/us/book/ swift-programming-language / id881256329?mt = 11
Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
这篇关于Swift类中的错误:属性未在super.init调用时初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!