Instruction 3

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Protocol Composition

The final feature you’ll learn in this lesson is protocol composition. Protocol composition allows you to combine multiple protocols at either the point of conformance or at the point of usage.

Unlike inheritance, which limits you to subclassing a single type, protocols offer the flexibility to conform to multiple interfaces. This enables you to integrate various unrelated protocols into a single type, each serving a specialized function. You can then combine these narrowly focused protocols in a cohesive manner where it’s beneficial.

To conform to multiple protocols, you add them as a comma-separated list. For example:

struct Movie: MediaItem, Codable, Sendable {
    // ...
}

This creates a Movie type that conforms to MediaItem, Codable and Sendable. Of course, you need to ensure you implement all the requirements for each protocol.

When defining a function that takes a type that conforms to multiple protocols, you can use & to combine them. For example:

func processItem(_ item: MediaItem & Codable) {
    
}

This function takes a type that must conform to MediaItem and Codable. If you try and pass it a type that doesn’t conform to both, you’ll get a compiler error.

See forum comments
Download course materials from Github
Previous: Demo 2 Next: Demo 3