In Swift, when do you write a protocol composition like `Codable & Sendable` instead of declaring a new protocol that inherits both?
answer
- a combination is not a new type
- how the standard library spells Codable
- conformance to a sub-protocol is declared
- at most one class in the list
basics
~20 sUse a composition such as Codable & Sendable when a value just needs several protocols at once: any type conforming to all of them qualifies. Declare an inheriting protocol for a named concept with its own requirements or extensions; conformers must adopt it explicitly.
solid answer
~50 sA **protocol composition** `A & B` behaves like a temporary protocol with the combined requirements but defines no new protocol type; any type that conforms to `A` and `B` satisfies it with no further declaration. The standard library uses one for `Codable`, which is `typealias Codable = Encodable & Decodable`. A **protocol that inherits** `A` and `B` is a new nominal type: it can add requirements, can be extended, and can be named in conformance lists, but a type that conforms to `A` and `B` does not conform to it until it says so ("does not conform to specified type 'CacheEntry'"). A composition may also include one class, as in `Location & Named`, and you cannot extend a composition ("non-nominal type cannot be extended"). Pick the composition for parameters and constraints; pick inheritance when the combination is a concept with its own requirements.
code
swift · 24 linesprotocol Evictable { var expiresAt: Double { get } }
protocol Sizable { var byteCount: Int { get } }
// A named protocol: a new type that conformers must name explicitly.
protocol CacheEntry: Evictable, Sizable {
var key: String { get } // inheritance can add requirements
}
// A composition: no new type, just "both at once".
typealias StorableEntry = Evictable & Sizable
struct Thumbnail: Evictable, Sizable, Codable, Sendable {
var expiresAt: Double
var byteCount: Int
}
func admit(_ entry: any Evictable & Sizable) -> Bool { entry.byteCount < 1_024 }
func persist<T: Codable & Sendable>(_ value: T) { print("persisting \(T.self)") }
let thumb = Thumbnail(expiresAt: 0, byteCount: 512)
print(admit(thumb)) // true: Thumbnail satisfies the composition as declared
persist(thumb)
// let entry: any CacheEntry = thumb
// error: Thumbnail never declared CacheEntry, so it does not conformgo deeper
Recall that & combines protocols at the use site and that Codable is a composition of Encodable and Decodable.
Explain the nominal rule: a composition is satisfied by any type conforming to every member, while an inheriting protocol must be adopted explicitly, and show the compile error that proves it.
Choose deliberately: compositions for parameters and constraints, inheriting protocols for concepts with added requirements or extensions, and plan the conformer edits a new sub-protocol forces.
Keep a module's protocol vocabulary small; promote a recurring composition to a named protocol only when it gains requirements or behaviour worth owning, since that costs every conformer an edit.
## Two ways to ask for several protocols Swift gives you two tools when a value must satisfy more than one protocol. - **Protocol inheritance**: `protocol CacheEntry: Evictable, Sizable { var key: String { get } }`. This declares a new **named protocol** that includes every requirement of `Evictable` and `Sizable` and may add its own. - **Protocol composition**: `Evictable & Sizable`. The Swift book describes it as behaving like a temporary local protocol with the combined requirements, while defining no new protocol type. You can list as many protocols as you need, joined by `&`. A composition can appear in most type positions: a parameter `any Evictable & Sizable`, a generic constraint `<T: Codable & Sendable>`, a property type, or a `typealias`. ## The decisive difference: who has to declare what Swift conformance is **nominal**: a type conforms to a protocol only when it, or an extension of it, says so. That rule cuts differently for the two tools: | Question | Composition `Evictable & Sizable` | Inheriting `protocol CacheEntry: Evictable, Sizable` | |---|---|---| | Does a type that conforms to both qualify automatically? | yes | no, it must declare `CacheEntry` | | Can it add its own requirements? | no | yes | | Can it be extended with `extension`? | no: "non-nominal type cannot be extended" | yes | | Can a conformance list name it? | yes, via a `typealias`, which conforms to each member | yes | The first row is where real bugs appear. Given `struct Thumbnail: Evictable, Sizable`, the call `admit(thumb)` with `func admit(_ entry: any Evictable & Sizable)` compiles, while `let entry: any CacheEntry = thumb` fails with "value of type 'Thumbnail' does not conform to specified type 'CacheEntry'". Introducing an inheriting protocol therefore means editing every conformer. ## The standard library's own choice `Codable` is not a protocol of its own. In `Codable.swift` it is declared as ```swift public typealias Codable = Encodable & Decodable ``` and its doc comment says that used as a type or constraint it matches any type conforming to both. That is why a type can adopt only `Decodable` when it never needs encoding, and why `Codable` itself cannot be extended as a protocol of its own. ## Compositions with a class A composition may contain **one class type**, naming a required superclass: `func beginConcert(in location: Location & Named)` accepts any `Location` subclass that also conforms to `Named`. Naming two classes is rejected: "protocol-constrained type cannot contain class 'B' because it already contains class 'A'". `AnyObject` can appear in a composition too, which restricts it to class instances. ## Mistakes that show up in review - Declaring `protocol CacheEntry: Evictable, Sizable {}` with no requirements of its own, then discovering every existing conformer must be edited before it can be passed where `any CacheEntry` is expected. - Assuming `Codable` can be extended like a protocol; extend `Encodable` or `Decodable` instead. - Putting two superclasses in one composition to say "either"; a composition always means *all of* its members. - Repeating a long composition at every call site instead of naming it once with a `typealias`. ## How to choose 1. **Reach for a composition** when a function or property merely needs several capabilities at once, such as `Codable & Sendable` for a value persisted from a background task. It costs conformers nothing. 2. **Declare an inheriting protocol** when the combination is a concept of its own: it adds requirements, deserves extensions with shared behaviour, or appears in documentation as a single idea. 3. **Give a recurring composition a `typealias`** so the spelling stays consistent, remembering that the alias is still just a composition. An interviewer is checking that you know a composition is structural over the listed protocols, an inheriting protocol is a new nominal type, and the difference shows up as compile errors when conformers have not opted in.
- Can a type declare conformance to a composition typealias such as `typealias StorableEntry = Evictable & Sizable`?Yes. `struct Blob: StorableEntry` conforms to `Evictable` and to `Sizable`, exactly as if both were listed; it is the same mechanism that lets types write `: Codable`. No third protocol exists, so nothing else changes.
- Why can you not write `extension Evictable & Sizable { ... }` to share an implementation?A composition is not a nominal type, and the compiler rejects it: "non-nominal type 'Evictable & Sizable' cannot be extended". To share behaviour for types that conform to both, extend one protocol with a constraint on the other, or declare an inheriting protocol and extend that.
- Codable is a protocol that inherits from Encodable and Decodable.
- A type conforming to A and B automatically conforms to any protocol inheriting both.
- A protocol composition can list any number of superclasses.
- You can add shared methods by extending A & B directly.
- A protocol composition defines a new protocol type.