所以我有以下超类:

class Vehicle {

    private var _maxSpeed: Int = 100

    var maxSpeed: Int {
        get {
            return _maxSpeed
        }

var tooFast: Bool {
        get {
            if maxSpeed >= 140 {
                return false
            } else {
                return true
            }
        }
    }
}

另外,我有一些子类,我想在其中重写maxspeed…每个示例:
class SuperCar: Vehicle {
//override the maxspeed...

}

但我该怎么处理呢?或者只有在我们不把它保密的情况下才有可能?我试着把私人部分扔出窗外,但效果不太好…
class Vehicle {

    var maxSpeed: Int = 100

var tooFast: Bool {
        get {
            if maxSpeed >= 140 {
                return false
            } else {
                return true
            }
        }
    }
}

class SuperCar: Vehicle {
// override the maxSpeed...
override var maxSpeed: Int = 200
// Will not work...
}

最佳答案

在init方法中设置私有成员变量

class Vehicle{
    private var maxSpeed: Int
    init(maxSpeed: Int = 100){
        self.maxSpeed = maxSpeed
    }
}

class SuperCar: Vehicle {
    override init(maxSpeed: Int = 200){
        super.init(maxSpeed: maxSpeed)
    }
}

10-06 09:27