0
0
Swiftprogramming~3 mins

Why Associated types in protocols in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one simple idea could make your code handle any type without rewriting everything?

The Scenario

Imagine you want to create a blueprint for different containers, like boxes or bags, that can hold any kind of item. Without a flexible way to say what type of item each container holds, you'd have to write a new blueprint for every single item type manually.

The Problem

Writing separate blueprints for each item type is slow and boring. It's easy to make mistakes, like mixing up item types or forgetting to update all versions. This manual approach wastes time and makes your code messy and hard to change.

The Solution

Associated types in protocols let you create one flexible blueprint that says, "I work with some type of item, but I don't care which one yet." This way, each container can specify its own item type when it's used, keeping your code clean and reusable.

Before vs After
Before
protocol BoxInt {
    func add(item: Int)
}

protocol BoxString {
    func add(item: String)
}
After
protocol Container {
    associatedtype Item
    func add(item: Item)
}
What It Enables

It enables writing one protocol that works with any type, making your code more flexible and easier to maintain.

Real Life Example

Think of a shopping cart that can hold groceries, clothes, or electronics. Using associated types, you can define one cart blueprint that adapts to whatever you put inside.

Key Takeaways

Manual type-specific protocols are repetitive and error-prone.

Associated types let protocols work with any type flexibly.

This makes your code cleaner, reusable, and easier to update.