Search code examples
swiftclasssubclassprivatesuperclass

How to override private var in superclass


So I have the following superclass:

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
            }
        }
    }
}

Plus I have some subclasses in which I want to override maxSpeed... per example:

class SuperCar: Vehicle {
//override the maxspeed...

}

But how should I approach this? Or is this only possible if we don't make it private? I tried to throw the private part out of the window but that won't work as well...

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

Solution

  • Set your private member variables in the init method

    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)
        }
    }