加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

属性 – Swift类中的错误:属性未在super.init调用初始化

发布时间:2020-12-14 06:16:57 所属栏目:百科 来源:网络整理
导读:我有两个类,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:
我有两个类,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
    }
}

使用上面的实现我得到错误:

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. 07000

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读