Protocol Composition
Protocol composition lets you say a type must check off items from more than one checklist at the same time, combining them with an ampersand.
Requiring Multiple Protocols with &
A function parameter typed as ProtocolA & ProtocolB accepts only values conforming to both protocols simultaneously.
Example: Requiring Multiple Protocols with &
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func describe(_ value: Named & Aged) -> String {
return "\(value.name) is \(value.age) years old"
}
let person = Person(name: "Lee", age: 40)
print(describe(person))
Login to try C/C++/Java/PHP code in the editor
Composition with Three or More Protocols
Protocol composition isn't limited to two protocols -- any number can be combined with additional & operators.
Example: Composition with Three or More Protocols
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }
protocol Employed { var job: String { get } }
struct Worker: Named, Aged, Employed {
var name: String
var age: Int
var job: String
}
func introduce(_ value: Named & Aged & Employed) {
print("\(value.name), \(value.age), works as \(value.job)")
}
introduce(Worker(name: "Kai", age: 33, job: "Engineer"))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to use inheritance-style syntax to require multiple protocols; composition uses
&between protocol names, not commas in a type annotation. - Forgetting a composed type (
ProtocolA & ProtocolB) requires an instance to conform to BOTH protocols, not just one of them. - Overcomplicating a function signature with many composed protocols when a single custom protocol combining the requirements would be clearer.
Chapter Summary
ProtocolA & ProtocolBdescribes a type conforming to both protocols at once.- This is commonly used as a parameter type to require multiple capabilities.
- Composition differs from class inheritance, which only allows one superclass.
- You can compose any number of protocols together with
&.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: