Class Inheritance Explained in Swift
In computer programming, the purpose of the superclass and subclass is to enable related classes to share functionalities.
Here’s an example!
class Dog {
var numberOfLegs = 4
func walk() {
print("I walk with \(numberOfLegs) legs")
}
}
class Poodle: Dog {}
var myPoodle = Poodle()
myPoodle.walk() // I walk with 4 legs
In this code, the Dog class has a numberOfLegs property with a value of 4 and a method named walk( ) that prints the number of legs the Dog walks with.
Then the Poodle class is created and it inherits from the Dog class. The syntax for when a class inherits from another is to follow the name of the subclass with a colon and then the superclass's name before the opening curly brace.
Next, the Poodle class is instantiated and the result is assigned to the variable named myPoodle.
Lastly, the walk( ) method is called on myPoodle and the output is the text: “I walk with 4 legs.”
Even though the Poodle class doesn’t define any methods or properties, it can access the numberOfLegs property and call the walk( ) method.
This is the beauty of class inheritance!
Note: To prevent a class from being subclassed, precede the name of the class with the final keyword.