Use Inheritance in Swift
Written by Team Kodeco
Inheritance in Swift allows a class to inherit the properties and methods of another class. It is used to create a hierarchical relationship between classes, where a subclass can inherit the characteristics of a superclass. The subclass can then add its own unique properties and methods, or override the ones inherited from the superclass.
Here’s an example of how to define a superclass and a subclass that inherits from it:
class Vehicle {
var wheels: Int
var weight: Double
var maxSpeed: Double
init(wheels: Int, weight: Double, maxSpeed: Double) {
self.wheels = wheels
self.weight = weight
self.maxSpeed = maxSpeed
}
func description() -> String {
return "A vehicle with \(wheels) wheels, weighs \(weight) kgs and has a maximum speed of \(maxSpeed) km/h."
}
}
class Car: Vehicle {
var numberOfDoors: Int
init(wheels: Int, weight: Double, maxSpeed: Double, doors: Int) {
self.numberOfDoors = doors
super.init(wheels: wheels, weight: weight, maxSpeed: maxSpeed)
}
}
This creates a new superclass called Vehicle
with properties for the number of wheels, weight and maximum speed. It also has a method called description
that returns a string with information about the vehicle.
Then, a new subclass called Car
is defined, which inherits from the Vehicle
class. It adds its own unique property for the number of doors and also overrides the init method to set the number of doors property.
You can create an instance of the Car class like this:
let myCar = Car(wheels: 4, weight: 1000, maxSpeed: 200, doors: 4)
And you can access the inherited properties and methods from the superclass like this:
print(myCar.wheels) // prints 4
print(myCar.description())
// prints "A vehicle with 4 wheels, weighs 1000.0 kgs and has a maximum speed of 200.0 km/h.
An analogy for inheritance might be a family tree. Just like a child inherits certain traits and characteristics from its parents, a subclass in Swift inherits certain properties and methods from its superclass.