skip to content

In a Swift protocol, how do you constrain an `associatedtype` with a protocol or a `where` clause, and what does that constraint buy?

level: middleimportance: should knowfreq 35%

answer

  1. a colon after the placeholder
  2. where relates two placeholders
  3. checked at every conformance
  4. extensions may rely on it
  5. Copyable is implied unless suppressed

basics

~20 s

Write a conformance after the name (associatedtype Entity: Identifiable) or a where clause relating it to another (where Batch.Element == Entity). Every conformer's choice is checked against it, and code written against the protocol may then use those guarantees.

solid answer

~40 s

An associated type takes the same kinds of constraints as a generic parameter. An inheritance clause, `associatedtype Entity: Identifiable`, requires the conformer's choice to conform; a `where` clause, `associatedtype Batch: Collection where Batch.Element == Entity`, ties it to another associated type. The compiler checks each conformance against them, so a `Note` that is not `Identifiable` cannot be a repository's `Entity`. In return, every protocol extension and generic algorithm may use `Entity.ID` or treat `all()` as a collection of entities without knowing the concrete types. Two refinements: a sub-protocol tightens an inherited associated type with a `where` clause on the protocol rather than redeclaring it, and every associated type is implicitly `Copyable` unless, since Swift 6.4, it is written `associatedtype Element: ~Copyable`.

code

swift · 23 lines
swift
protocol Repository {
    associatedtype Entity: Identifiable
    associatedtype Batch: Collection where Batch.Element == Entity
    func find(id: Entity.ID) -> Entity?
    func all() -> Batch
}

extension Repository {
    // Compiles only because the constraints promise that Batch holds
    // Entity values and that every Entity has an id.
    func allIDs() -> [Entity.ID] { all().map(\.id) }
}

struct Note: Identifiable { let id: Int; var text: String }

struct NoteRepository: Repository {
    var notes: [Note] = []
    func find(id: Int) -> Note? { notes.first { $0.id == id } }
    func all() -> [Note] { notes }
}

let repo = NoteRepository(notes: [Note(id: 1, text: "a"), Note(id: 2, text: "b")])
print(repo.allIDs())   // Prints "[1, 2]"

go deeper

for a junior

Recall that an associatedtype can be followed by a colon and a protocol, just like a generic parameter, to limit what conformers may choose.

for a middle

Explain the where clause on an associated type, how the compiler checks it at conformance time, and which extension code the guarantee makes legal.

for a senior

Read the inference notes when a constraint fails, refine inherited associated types with protocol where clauses, and know the implicit Copyable constraint and its 6.4 suppression.

for a principal

Balance how tightly a shared protocol constrains its associated types: each constraint unlocks shared algorithms but shuts out conformers a future team may need.

## Two ways to constrain an associated type An **associated type** is a placeholder each conforming type fills in. Left bare, it can be anything, and code written against the protocol can do almost nothing with it. Swift lets the protocol constrain it in two ways: 1. **An inheritance clause** names protocols (or a superclass) the chosen type must satisfy: `associatedtype Entity: Identifiable`. 2. **A generic `where` clause** on the associated type states relationships, usually same-type requirements between associated types: `associatedtype Batch: Collection where Batch.Element == Entity`. ```swift protocol Repository { associatedtype Entity: Identifiable associatedtype Batch: Collection where Batch.Element == Entity func find(id: Entity.ID) -> Entity? func all() -> Batch } ``` The standard library leans on this heavily. `Collection` declares `associatedtype SubSequence: Collection = Slice<Self>` followed by a `where` clause requiring the subsequence to share the collection's `Index` and `Element`, so a slice always uses its base collection's index type. A `where` clause may even mention the protocol being declared, as The Swift Programming Language shows with a container whose `Suffix` must itself be a container of the same `Item`. ## What conformers must satisfy The constraints are checked **once, at the conformance**, against whatever the conformer picked or the compiler inferred. If a `NoteRepository` returns `Note?` from `find(id:)` but `Note` is not `Identifiable`, the conformance fails at compile time: ```plaintext error: type 'NoteRepository' does not conform to protocol 'Repository' note: candidate would match and infer 'Entity' = 'Note' if 'Note' conformed to 'Identifiable' ``` Nothing is deferred to run time: there is no trap and no fallback type. ## What the constraint buys The pay-off is on the other side. Inside the protocol, its extensions and any generic code constrained to it, the compiler may assume every guarantee the constraints state: - `Entity: Identifiable` means `Entity.ID` exists and is `Hashable`, so `find(id: Entity.ID)` and a dictionary keyed by ID are legal. - `Batch: Collection where Batch.Element == Entity` means `all()` can be iterated, counted and mapped, and its elements are entities. - A default implementation such as `func allIDs() -> [Entity.ID] { all().map(\.id) }` compiles once for every conformer, because the constraints prove it is safe. Without the constraints, the same extension would not compile: the compiler cannot assume a bare `Entity` has an `id`, or that a bare `Batch` can be mapped. | Declared as | Conformer may pick | Protocol code may assume | |---|---|---| | `associatedtype Entity` | any copyable type | only the implicit `Copyable` and `Escapable` | | `associatedtype Entity: Identifiable` | an `Identifiable` type | `Entity.ID`, a `Hashable` identifier | | `associatedtype Batch: Collection where Batch.Element == Entity` | a collection of entities | iteration, `count`, elements are `Entity` | ## Refining an inherited associated type A protocol that inherits from another should tighten the parent's associated type with a `where` clause on the protocol, `protocol SubProtocolB: SomeProtocol where SomeType: Equatable { }`. Redeclaring it, `associatedtype SomeType: Equatable`, still compiles but warns: "redeclaration of associated type 'SomeType' from protocol 'SomeProtocol' is better expressed as a 'where' clause on the protocol". ## The implicit Copyable constraint and Swift 6.4 Every associated type also carries an **implicit** constraint: it must be `Copyable` (and `Escapable`). Before Swift 6.4 no shipped release could remove it, so a noncopyable `Ticket` could not be a protocol's `Element` even when the protocol never copied it. Swift 6.4 (SE-0503) lets the protocol suppress it: `associatedtype Element: ~Copyable`, read "maybe copyable", allows both copyable and noncopyable choices. A requirement that takes such an element as a parameter must then state its ownership, such as `consuming` or `borrowing`; otherwise the compiler reports "parameter of noncopyable type 'Self.Element' must specify ownership". Interviews rarely reach this; it matters mostly to library authors. ## Pitfalls - Constraining too little and then writing extensions that need a cast; constrain what the algorithms rely on. - Constraining too much: every constraint narrows which types can conform. - Expecting a missing conformance to show up at run time; it is always a compile-time conformance error. - Assuming `~Copyable` *requires* a noncopyable type; it only stops requiring a copyable one. - Forgetting that a constraint added to a published protocol later is a breaking change: every existing conformer whose choice does not satisfy it stops compiling. The habit that serves best is to read each constraint as a contract with two sides: conformers must meet it, and every piece of code written against the protocol may rely on it.

  • How should a Swift protocol that inherits from another tighten the parent's associated type?
    Put a `where` clause on the inheriting protocol: `protocol SubProtocolB: SomeProtocol where SomeType: Equatable { }`. Redeclaring `associatedtype SomeType: Equatable` in the child compiles but triggers the warning that the redeclaration "is better expressed as a 'where' clause on the protocol".
  • Why could a protocol before Swift 6.4 not accept a noncopyable type as its associated type?
    Noncopyable generics (SE-0427) gave every associated type an implicit `Copyable` requirement with no way to suppress it. Swift 6.4 (SE-0503) allows `associatedtype Element: ~Copyable`, so a conformer may pick a noncopyable `Element`; parameters of that type must then say `consuming` or `borrowing`.
  • Can a `where` clause on an associated type refer to the protocol being declared?
    Yes, recursive constraints are allowed. `Collection` itself declares `associatedtype SubSequence: Collection = Slice<Self>` with a `where` clause requiring matching `Index` and `Element`, so a slice is itself a collection with its parent's `Index` and `Element` types.

  • An associatedtype cannot carry constraints; only generic parameters can.
  • A conformer that breaks an associated-type constraint fails at run time, not compile time.
  • A protocol extension cannot use members guaranteed by an associated type's constraint.
  • Redeclaring an inherited associatedtype with a new constraint is the preferred refinement.
  • Since Swift 6.4 every associated type accepts noncopyable types by default.

Assumes Swift 6.4; suppressing Copyable on an associated type (associatedtype Element: ~Copyable, SE-0503) is new in 6.4, while the other constraint forms work in every supported release.