Introduction
Protocol inheritance lets one protocol build on another. It helps organize shared rules simply and clearly.
Protocol inheritance lets one protocol build on another. It helps organize shared rules simply and clearly.
protocol NewProtocol: ExistingProtocol { // additional requirements }
Car inherits from Vehicle. So, any Car must start its engine and open the trunk.protocol Vehicle { func startEngine() } protocol Car: Vehicle { func openTrunk() }
FlyingCar inherits from both Drivable and Flyable. It must implement all their methods plus switchMode().protocol Drivable { func drive() } protocol Flyable { func fly() } protocol FlyingCar: Drivable, Flyable { func switchMode() }
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.
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())
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.
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.
AdvancedProtocol that inherits from BasicProtocol in Swift?protocol NewProtocol: ExistingProtocol {}.example.printInfo() is called?protocol A {
func printInfo()
}
protocol B: A {
func printExtra()
}
class Example: B {
func printInfo() {
print("Info from A")
}
func printExtra() {
print("Extra from B")
}
}
let example = Example()
example.printInfo()printInfo() and printExtra(). It does.example.printInfo(), which prints "Info from A".protocol P1 {
func method1()
}
protocol P2: P1 {
func method2()
}
class MyClass: P2 {
func method2() {
print("Method 2")
}
}method2() but misses method1(), causing a compile error.protocol Vehicle {
func start()
}
protocol ElectricVehicle: Vehicle {
func charge()
}ElectricCar that conforms to ElectricVehicle. Which implementation correctly satisfies all protocol requirements?start() and charge().charge() or start(). class ElectricCar: Vehicle {
func charge() { print("Charging") }
} does not conform to ElectricVehicle.Pass the test and this pattern moves unknown