我有两门课,形状和正方形

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)

为什么我要设置self。调用super.init之前的sidelth ?


当前回答

应该是这样的:

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

看看这个链接: https://swiftgg.gitbook.io/swift/swift-jiao-cheng/14_initialization#two-phase-initialization

其他回答

在声明的末尾添加nil。


// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil

// Init the view
override init(frame: CGRect)
    super.init(frame: frame)
    ...

这对我的案子有用,但对你的可能没用

Swift强制你在使用/可能使用之前初始化每个成员var。因为它不能确定当它变成超级时发生了什么,所以它会出错:小心总比后悔好

应该是这样的:

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

看看这个链接: https://swiftgg.gitbook.io/swift/swift-jiao-cheng/14_initialization#two-phase-initialization

爱德华,

你可以像这样修改你的例子中的代码:

var playerShip:PlayerShip!
var deltaPoint = CGPointZero

init(size: CGSize)
{
    super.init(size: size)
    playerLayerNode.addChild(playerShip)        
}

这使用了一个隐式解包装的可选选项。

在文档中我们可以读到:

与可选选项一样,如果你不提供初始值 声明一个隐式展开的可选变量或属性,它是 Value自动默认为nil。”

你只是开始的顺序不对。

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

    class Square2: Shape2 {
        var sideLength: Double

        init(sideLength:Double, name:String) {

            self.sideLength = sideLength
            super.init(name:name) // It should be behind "self.sideLength = sideLength"
            numberOfSides = 4
        }
        func area () -> Double {
            return sideLength * sideLength
        }
    }