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

时间:2014-08-16 01:34:49

标签: ios macos swift swift-playground

我正在尝试初始化如下的子类:

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: 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)."
    }

}

现在很好,有人可以解释背后的原理吗? THX !!!

1 个答案:

答案 0 :(得分:1)

你改变它的原因是因为Apple" safe"接近这种语言。在方法调用之前未初始化的任何非包装和非初始化变量都将引发编译器错误。它是Swift的安全功能。基本上,编译器试图阻止你做这样的事情:

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

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