0
0
Swiftprogramming~3 mins

Why Protocol with associated types in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one blueprint that magically fits any kind of item without rewriting your code?

The Scenario

Imagine you want to create a blueprint for different containers, like boxes or bags, that can hold items. You try to write separate code for each container type and the items they hold.

The Problem

Writing separate code for each container and item type quickly becomes messy and repetitive. You have to rewrite similar logic for each new container, making your code hard to maintain and easy to break.

The Solution

Protocols with associated types let you define a flexible blueprint that can work with any item type. This way, you write the container logic once, and it adapts to hold any kind of item without repeating code.

Before vs After
Before
struct BoxInt { var item: Int }
struct BoxString { var item: String }
After
protocol Container { associatedtype Item
var item: Item { get set } }
struct Box<T>: Container { var item: T }
What It Enables

This concept lets you write adaptable, reusable code that works with many types while keeping your code clean and easy to understand.

Real Life Example

Think of a vending machine that can hold different snacks. Using protocols with associated types, you can create one vending machine design that works for chips, candy, or drinks without rewriting the whole machine for each snack.

Key Takeaways

Manual code for each type is repetitive and hard to maintain.

Protocols with associated types create flexible blueprints for many types.

This leads to cleaner, reusable, and adaptable code.