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.swift372 chars20 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