What if you could write one blueprint that magically fits any kind of item without rewriting your code?
Why Protocol with associated types in Swift? - Purpose & Use Cases
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.
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.
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.
struct BoxInt { var item: Int }
struct BoxString { var item: String }protocol Container { associatedtype Item
var item: Item { get set } }
struct Box<T>: Container { var item: T }This concept lets you write adaptable, reusable code that works with many types while keeping your code clean and easy to understand.
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.
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.