Junior — Middle
Is it possible to implement multiple inheritance from several classes simultaneously in Swift?
sobes.tech AI
Answer from AI
In Swift, it is not possible to inherit from multiple classes simultaneously, meaning multiple inheritance of classes is not supported. A class can have only one parent. Instead, Swift uses protocols to achieve similar functionality — a class can implement multiple protocols, allowing the addition of various behaviors and properties without multiple inheritance.
Example of protocol implementation:
protocol Drivable {
func drive()
}
protocol Flyable {
func fly()
}
class Vehicle: Drivable {
func drive() {
print("Driving")
}
}
class FlyingCar: Vehicle, Flyable {
func fly() {
print("Flying")
}
}
let car = FlyingCar()
car.drive() // Driving
car.fly() // Flying
Thus, Swift encourages composition through protocols instead of multiple class inheritance.