What if you could write a piece of code once and have it work everywhere without repeating yourself?
Why Protocol extensions with default implementations in Swift? - Purpose & Use Cases
Imagine you have many different types of vehicles, and you want each to have a way to start the engine. You write the same start code inside every vehicle class manually.
This means repeating the same code over and over. If you want to change how starting works, you must update every class separately. It's slow, boring, and easy to make mistakes.
Protocol extensions with default implementations let you write the start code once. All vehicle types that follow the protocol get this code automatically, unless they want to customize it.
class Car { func start() { print("Engine started") } } class Bike { func start() { print("Engine started") } }
protocol Vehicle { func start() }
extension Vehicle { func start() { print("Engine started") } }
class Car: Vehicle {}
class Bike: Vehicle {}This lets you add shared behavior easily and keep your code clean, saving time and avoiding errors.
Think of a game where many characters can attack. Using protocol extensions, you write the attack once and all characters get it, but some can still have special attacks.
Writing shared code once for many types.
Saving time and reducing mistakes.
Allowing easy customization when needed.