override a property on a subclass in swift

In Swift, you can override a property that is defined in a superclass by declaring it again with the override keyword in the subclass. Here's an example:

main.swift
class Vehicle {
    var speed: Double = 0
    
    func accelerate() {
        speed += 10
    }
}

class Car: Vehicle {
    override var speed: Double {
        didSet {
            print("The car's speed is now \(speed) mph.")
        }
    }
}

let myCar = Car()
myCar.accelerate() // the car's speed is now 10 mph.
myCar.accelerate() // the car's speed is now 20 mph.
372 chars
20 lines

In this example, Vehicle is the superclass and Car is the subclass that inherits from Vehicle. Vehicle has a property speed that holds the current speed of the vehicle, and a method accelerate that increases the speed by 10.

In the Car subclass, we override the speed property with a computed property that has a didSet observer. This means that whenever the speed property is set in Car, the didSet observer will be called and print the new speed.

When we create an instance of Car and call the accelerate method, the speed property is updated and the didSet observer is called to print the new value.

gistlibby LogSnag