0
0
Swiftprogramming~5 mins

Protocol inheritance in Swift

Choose your learning style9 modes available
Introduction

Protocol inheritance lets one protocol build on another. It helps organize shared rules simply and clearly.

When you want a new protocol to include all rules from an existing protocol plus more.
When you want to group related behaviors in a clear way.
When you want to make sure a type follows multiple sets of rules by combining protocols.
When you want to avoid repeating the same requirements in many protocols.
Syntax
Swift
protocol NewProtocol: ExistingProtocol {
    // additional requirements
}
A protocol can inherit from one or more protocols by listing them after a colon.
The new protocol includes all requirements from the inherited protocols.
Examples
Car inherits from Vehicle. So, any Car must start its engine and open the trunk.
Swift
protocol Vehicle {
    func startEngine()
}

protocol Car: Vehicle {
    func openTrunk()
}
FlyingCar inherits from both Drivable and Flyable. It must implement all their methods plus switchMode().
Swift
protocol Drivable {
    func drive()
}

protocol Flyable {
    func fly()
}

protocol FlyingCar: Drivable, Flyable {
    func switchMode()
}
Sample Program

Here, Pet inherits from Animal. The Dog struct must implement both sound() and play(). We create a dog and print its sound and play behavior.

Swift
protocol Animal {
    func sound() -> String
}

protocol Pet: Animal {
    func play() -> String
}

struct Dog: Pet {
    func sound() -> String {
        return "Bark"
    }
    func play() -> String {
        return "Fetch the ball"
    }
}

let myDog = Dog()
print(myDog.sound())
print(myDog.play())
OutputSuccess
Important Notes

Protocols can inherit from multiple protocols by separating them with commas.

Any type conforming to a protocol that inherits others must implement all requirements from all protocols.

Summary

Protocol inheritance lets you build new protocols from existing ones.

It helps keep code organized and avoids repeating requirements.

Types conforming to inherited protocols must implement all combined requirements.