Error in Swift class: Property not initialized at super.init call(Swift 类中的错误:在 super.init 调用时未初始化属性)
问题描述
我有两个类,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)
为什么我必须在调用 super.init 之前设置 self.sideLength?
Why do I have to set self.sideLength before calling super.init?
推荐答案
引自 The Swift Programming Language,它回答了你的问题:
Quote from The Swift Programming Language, which answers your question:
Swift 的编译器会执行四项有用的安全检查,以确保两阶段初始化完成,没有错误:"
"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 编程语言".电子书.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 调用时未初始化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift 类中的错误:在 super.init 调用时未初始化属性
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
