0Pricing
Swift Academy · Lesson

Protocol Composition

Combine multiple protocol requirements with &.

Combining Protocols

Sometimes a value must satisfy several protocols at once. Swift lets you compose protocols with the & operator: SomeProtocol & AnotherProtocol.

protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }

A Composed Parameter

A parameter typed Named & Aged accepts any value that conforms to both protocols.

protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }

struct Person: Named, Aged {
    let name: String
    let age: Int
}

func intro(_ x: Named & Aged) {
    print(x.name + " is " + String(x.age))
}
intro(Person(name: "Sam", age: 28))

All lessons in this course

  1. Protocols as Contracts
  2. Default Implementations in Extensions
  3. Protocol Composition
  4. Conditional Conformance
← Back to Swift Academy