Swift Inheritance
In Swift, a class can inherit properties and methods from another class, which is known as inheritance. This allows the child class (also known as the subclass) to reuse the functionality of the parent class (also known as the superclass), and to extend or modify that functionality as needed.
Here is an example of how to define a superclass and a subclass in Swift:
class Vehicle {
var numberOfWheels: Int
var color: String
init(numberOfWheels: Int, color: String) {
self.numberOfWheels = numberOfWheels
self.color = color
}
func startEngine() {
print("Vroom!")
}
}
class Bicycle: Vehicle {
var hasBasket: Bool
init(numberOfWheels: Int, color: String, hasBasket: Bool) {
self.hasBasket = hasBasket
super.init(numberOfWheels: numberOfWheels, color: color)
}
override func startEngine() {
// Bicycles don't have engines, so we'll just print a message instead
print("Pedaling along...")
}
}
In this example, the Vehicle
class is the superclass, and the Bicycle
class is the subclass. The Bicycle
class inherits the numberOfWheels
and color
properties, as well as the startEngine()
method from the Vehicle
class. It also adds its own hasBasket
property and overrides the startEngine()
method to provide its own implementation.
You can then create instances of the Bicycle
class and use them like this:
let myBike = Bicycle(numberOfWheels: 2, color: "red", hasBasket: true)
myBike.startEngine() // Output: "Pedaling along..."
In this code, the myBike
variable is an instance of the Bicycle
class, which inherits the properties and methods of the Vehicle
class and provides its own implementation of the startEngine()
method. When you call the startEngine()
method on the myBike
instance, it uses the implementation provided by the Bicycle
class, which prints the message “Pedaling along…”.