← Back to Swift Course | Chapter 9: Inheritance & Protocols | Lesson 7 of 7

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 &

markup
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))

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

markup
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"))
Common Mistakes
  1. Trying to use inheritance-style syntax to require multiple protocols; composition uses & between protocol names, not commas in a type annotation.
  2. Forgetting a composed type (ProtocolA & ProtocolB) requires an instance to conform to BOTH protocols, not just one of them.
  3. Overcomplicating a function signature with many composed protocols when a single custom protocol combining the requirements would be clearer.
Chapter Summary
  • ProtocolA & ProtocolB describes 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.