Sobes.tech
Junior — Middle

Is it possible to implement multiple inheritance in Swift?

sobes.tech AI

Answer from AI

In Swift, multiple inheritance of classes is not supported. A class can only inherit from one superclass. However, Swift provides the ability to implement functionality similar to multiple inheritance through protocols.

Protocols allow you to define a set of methods and properties that a class, struct, or enum must implement. A class can conform to multiple protocols, thus combining different behaviors.

Example:

protocol Drivable {
    func drive()
}

protocol Flyable {
    func fly()
}

class Vehicle {
    func start() {
        print("Vehicle started")
    }
}

class FlyingCar: Vehicle, Drivable, Flyable {
    func drive() {
        print("Driving on the road")
    }
    
    func fly() {
        print("Flying in the sky")
    }
}

Thus, Swift uses composition through protocols instead of multiple inheritance.