What if one simple idea could make your code handle any type without rewriting everything?
Why Associated types in protocols in Swift? - Purpose & Use Cases
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.
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.
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.
protocol BoxInt {
func add(item: Int)
}
protocol BoxString {
func add(item: String)
}protocol Container {
associatedtype Item
func add(item: Item)
}It enables writing one protocol that works with any type, making your code more flexible and easier to maintain.
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.
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.