Overriding methods and properties
To override a method, property, or subscript, we need to prefix the definition with the override
keyword. This tells the compiler that we intend to override something in the super class and that we did not make a duplicate definition by mistake. The override
keyword prompts the Swift compiler to verify that the super class (or one of its parents) has a matching declaration that can be overridden. If it cannot find a matching declaration in one of the super classes, an error will be thrown.
Overriding methods
Let's look at how we would override a method. We will start by adding a getDetails()
method to the Plant
class that we will then override in the child classes. The following code shows how the new Plant
class looks with the getDetails()
method added:
class Plant { var height = 0.0 var age = 0 func growHeight(inches: Double) { self.height += inches; } func getDetails() -> String { ...