How to change the default value of a property in a subclass belonging to a parent class?

Hello, I’m wondering if it’s possible to change the default property of a subclass. Specifically, if a parent class has a property with a default value, and I want to create a subclass that will inherit that property, but use a different default value specific to the subclass – is that even possible? I tried to do that with the below code and it’s not working for me.

class Spaceship {
    
    var fuelLevel: Int = 50
    

    func liftOff() {
        fuelLevel -= 50
        print("We have lift off!")
        print("Current fuel level is at: \(fuelLevel)")
    }

    func addFuel(fuel: Int) {
        fuelLevel += fuel
        print("Fuel added!")
        print("Current fuel leel is at: \(fuelLevel)")
    }


    func thrust() {
        fuelLevel -= 15
        print("Rocket is thrusting!")
        print("Current fuel level is at: \(fuelLevel)")
    }

    func cruise() {
        fuelLevel -= 5
        print("Rocket is cruising!")
        print("Current fuel level is at: \(fuelLevel)")
    }
    
}


class UFOShip: Spaceship {
    
    fuelLevel = 25
    
    func float() {
        print("The UFO is now floating!")
    }
    
    override func cruise() {
       fuelLevel -= 2
        print("The UFO is now cruising along!")
         print("The current fuel level is at \(fuelLevel)")
    }
}

var myNewUFO = UFOShip()

myNewUFO.cruise()

You can’t assign a value to a property at the top level of your class.

To fix, do this:

Replace the line fuelLevel = 25 with:

    override init() {
        super.init()
        fuelLevel = 25
    }

This initializes the parent class, then sets a new value for fuelLevel for the subclass.

What is the purpose of init() here? I understand that it is an initializer but I am having trouble understanding its purpose here. Could you please explain how I would “read” the code you suggested?

Initializers are used to set the default values of stored properties. This can also be done by providing a default as you have done in Spaceship. The problem here with doing that in UFOShip is that you cannot override the value of a property in a superclass with a stored property in the subclass.

The way you can do it is by setting the value of the property in the subclass’ initializer. So in the code I posted, UFOShip.init() first calls the init of its superclass (Spaceship), which sets fuelLevel to 50, then overrides that value by setting it to 25.