0
0
Swiftprogramming~3 mins

Why Protocol extensions with default implementations in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a piece of code once and have it work everywhere without repeating yourself?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
class Car { func start() { print("Engine started") } } 
class Bike { func start() { print("Engine started") } }
After
protocol Vehicle { func start() }
extension Vehicle { func start() { print("Engine started") } }
class Car: Vehicle {}
class Bike: Vehicle {}
What It Enables

This lets you add shared behavior easily and keep your code clean, saving time and avoiding errors.

Real Life Example

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.

Key Takeaways

Writing shared code once for many types.

Saving time and reducing mistakes.

Allowing easy customization when needed.