Sobes.tech
Junior — Middle

Kuidas saavutatakse Swift keeles mitmekordne pärimine klasside või protokollide kaudu?

sobes.tech AI

Vastus AI-lt

In Swift, a class can only inherit from one superclass, meaning multiple inheritance of classes is not supported. However, to achieve a similar effect, inheritance from one class and implementation of multiple protocols are used. Protocols in Swift define a set of requirements (methods, properties) that a class, struct, or enumeration must implement. This way, a class can inherit behavior from a superclass and simultaneously conform to multiple protocols, allowing for the combination of functionalities.

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")
    }
}

let myFlyingCar = FlyingCar()
myFlyingCar.start()  // Vehicle started
myFlyingCar.drive()  // Driving on the road
myFlyingCar.fly()    // Flying in the sky

Thus, multiple inheritance is achieved through inheriting from one class and implementing multiple protocols.