What if you could mix and match abilities in your code as easily as picking toppings on a pizza?
Why Protocol composition in practice in Swift? - Purpose & Use Cases
Imagine you have several roles in a team, like a coder, a tester, and a designer. You want to assign tasks to people who can do multiple roles, but you write separate code for each role combination.
This manual way means writing many repeated checks and classes for every possible role mix. It gets messy, slow to update, and easy to make mistakes when roles change.
Protocol composition lets you combine multiple roles into one requirement easily. You write clean code that says, "I need someone who is both a coder and a tester," without making new classes for every mix.
protocol Coder { func code() }
protocol Tester { func test() }
class CoderTester: Coder, Tester {
func code() {}
func test() {}
}func assignTask(to person: Coder & Tester) {
person.code()
person.test()
}It enables writing flexible, clear, and reusable code that works with any combination of capabilities without extra classes.
In an app, you might want a function that accepts any object that can both draw and animate. Protocol composition lets you require both abilities simply and safely.
Manual role combinations cause repeated, hard-to-maintain code.
Protocol composition combines multiple protocols into one easy requirement.
This leads to cleaner, more flexible, and reusable code.