Discover how protocol inheritance saves you from writing the same code over and over!
Why Protocol inheritance in Swift? - Purpose & Use Cases
Imagine you have several types of vehicles, and you want to define common features like starting the engine and honking. Without protocol inheritance, you'd have to write these features separately for each vehicle type or copy them into multiple protocols.
This manual approach is slow and error-prone because you repeat code and risk inconsistencies. If you want to add a new common feature, you must update every protocol and type separately, which is tedious and confusing.
Protocol inheritance lets you create a base protocol with common features, then build other protocols on top of it. This way, you write shared requirements once and reuse them, making your code cleaner and easier to maintain.
protocol EngineStartable { func startEngine() }
protocol Honkable { func honk() }
protocol CarProtocol { func startEngine(); func honk() }protocol VehicleProtocol { func startEngine() }
protocol CarProtocol: VehicleProtocol { func honk() }It enables you to organize and reuse common behaviors across multiple protocols effortlessly, keeping your code simple and scalable.
Think of a game where different characters share basic actions like moving and jumping. Protocol inheritance lets you define these actions once and then add special moves for each character type without repeating code.
Protocol inheritance helps avoid repeating common code.
It makes adding new shared features easy and consistent.
Your code becomes cleaner, easier to read, and maintain.