Inheritance is a key feature in object-oriented programming that allows a class to inherit properties and methods from another class. In Swift, classes can inherit from a single superclass, making it a great way to reuse code and create a hierarchy of related classes. Let's explore how to work with inheritance in Swift with a simple example:
// Defining a superclass
class Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
}
func drive() {
print("The \(brand) is driving")
}
}
// Creating a subclass
class Car: Vehicle {
var model: String
init(brand: String, model: String) {
self.model = model
super.init(brand: brand)
}
func honk() {
print("The \(brand) \(model) is honking")
}
}
// Using inheritance
let myCar = Car(brand: "Toyota", model: "Corolla")
myCar.drive()
myCar.honk()}
In the code snippet above, we have a `Vehicle` class as the superclass and a `Car` class as a subclass that inherits from `Vehicle`. The `Car` class has its own property `model` and method `honk`, while also inheriting the `drive` method from the `Vehicle` class.
When creating an instance of `Car`, we instantiate it with both the `brand` and `model` properties. We can then call methods from both the superclass and the subclass on the instance.
Working with inheritance in Swift allows for code reusability and promotes a hierarchical organization of classes. It is essential to understand how inheritance works to effectively structure your Swift codebase.