What if you could ask for multiple skills at once without messy checks?
Why Protocol composition in Swift? - Purpose & Use Cases
Imagine you have several roles in a team, like a designer and a developer. You want to assign tasks only to people who can do both jobs. Without a clear way to combine these roles, you have to check each person manually every time.
Manually checking if someone fits multiple roles is slow and error-prone. You might forget a check or write repetitive code for each combination, making your program messy and hard to maintain.
Protocol composition lets you combine multiple protocols into one requirement. This way, you can easily say "I need someone who is both a designer and a developer" without writing extra checks. It keeps your code clean and clear.
func assignTask(person: Designer) {
if let dev = person as? Developer {
// assign task
}
}func assignTask(person: Designer & Developer) {
// assign task directly
}It enables writing concise, readable code that clearly expresses combined capabilities without extra checks.
In an app, you might want to update UI elements only if the object can both display and animate. Protocol composition lets you require both abilities at once, making your code safer and simpler.
Manually combining roles is slow and error-prone.
Protocol composition combines multiple protocols into one requirement.
This leads to cleaner, easier-to-read code that expresses combined abilities clearly.