skip to content

Before Swift 5.7, why could a protocol with an `associatedtype` or `Self` requirement be used only as a generic constraint, and what is still restricted today?

level: seniorimportance: must knowfreq 55%

answer

  1. what is Entity inside a box?
  2. SE-0309 in Swift 5.7
  3. parameter versus result position
  4. erased to the upper bound

basics

~20 s

A protocol-typed value hides its concrete type, so Swift cannot know what Entity or Self means there. Before 5.7 such protocols were rejected as types; now any Repository compiles, but members taking Entity or Self as parameters stay unusable.

solid answer

~50 s

A protocol type is a box that can hold any conformer, so for a `Repository` with `associatedtype Entity`, the box does not know whether it holds users or orders. Calling `save(_:)` on it would let you pass a `User` into an order repository, so the compiler had no sound type for `Entity` there; before Swift 5.7 it refused the protocol as a type altogether, and you had to write generic code such as `<R: Repository>` or a hand-written eraser. Swift 5.7 (SE-0309) allows `any Repository`, but only members that are safe on the box are usable: `count` works, `find(id:)` returning `Entity?` works with the result erased to the associated type's upper bound (`Any?` here), and `save(_:)` is rejected with "member 'save' cannot be used on value of type 'any Repository'; consider using a generic constraint instead". The same rule makes `==` unavailable between two `any Equatable` values.

code

swift · 20 lines
swift
struct User { let id: Int }

protocol Repository {
    associatedtype Entity
    var count: Int { get }
    func find(id: Int) -> Entity?
    mutating func save(_ entity: Entity)
}

struct UserRepository: Repository {
    var users: [User] = []
    var count: Int { users.count }
    func find(id: Int) -> User? { users.first { $0.id == id } }
    mutating func save(_ entity: User) { users.append(entity) }
}

var repositories: [any Repository] = [UserRepository()]
print(repositories[0].count)            // fine: no Entity in the signature
let hit = repositories[0].find(id: 1)   // fine: Entity? is erased to Any?
repositories[0].save(User(id: 1))       // error: Entity in parameter position

go deeper

for a junior

Recall that a protocol with an associatedtype could not be used as a variable's type before Swift 5.7 and that generic code was the workaround.

for a middle

Explain why the box cannot know what Entity or Self means, and which members are still callable on an any type since Swift 5.7.

for a senior

Predict, from a member's signature, whether it is usable on an existential, read the ExistentialMemberAccess diagnostic, and choose between generics, constrained existentials and erasers.

for a principal

Judge where a codebase's APIs should take generics instead of existentials for protocols with associated types, given readability, flexibility and specialization.

## The problem: a box hides the conformer Using a protocol **as a type**, for example as an array element type, creates an **existential**: a box that can hold a value of any conforming type and hides which one. For most protocols that is harmless. For a protocol with an **associated type** or a **Self requirement**, the box loses information the requirements depend on. Take a `Repository` whose conformers each store one `Entity` type. A `UserRepository` stores `User`; an `OrderRepository` stores `Order`. Put both in one array of repositories and ask: what is `Entity` for `repositories[0]`? The answer depends on the run-time value. Now call `repositories[0].save(someUser)`. If the box holds an `OrderRepository`, a `User` would be saved into an order store. The type checker cannot prove that call safe, so it must reject it. The same reasoning applies to `Self`. `Equatable`'s `==` takes two values of type `Self`. Two boxes of type `any Equatable` might hold an `Int` and a `String`, so `==` between them has no sound meaning. ## Before Swift 5.7 Older compilers took the blunt route. Any protocol with an associated type or a `Self` requirement could not be used as a type at all; the compiler rejected the declaration with an error saying the protocol can only be used as a generic constraint because it has Self or associated type requirements. Teams worked around it in two ways: - **Generic code**: `func importAll<R: Repository>(_ items: [R.Entity], into repo: inout R)`. Inside a generic function the concrete type is fixed per call, so `R.Entity` is known and every requirement is usable. - **Type erasers**: hand-written wrapper structs, in the spirit of the standard library's `AnySequence` and `AnyHashable`, that hold the wrapped value or closures and forward each call. Writing them belongs to the lesson on opaque and existential types. ## What Swift 5.7 changed Swift 5.7 implemented **SE-0309**, which unlocked existential types for all protocols. Instead of sealing off the whole protocol, the compiler now restricts only the *members* whose signatures cannot be expressed on a box. The same release required the `any` keyword (introduced in Swift 5.6 by SE-0335) when such protocols are written as types; since Swift 6.1 a missing `any` is downgraded to a warning, "use of protocol 'Repository' as a type must be written 'any Repository'; this will be an error in a future Swift language mode". The surviving rule depends on **where** `Self` or an associated type appears in a member's signature: | Member | Signature mentions `Entity`/`Self`? | Usable on `any Repository`? | |---|---|---| | `var count: Int { get }` | no | yes | | `func find(id: Int) -> Entity?` | in the result only | yes, result erased to `Any?` | | `func copy() -> Self` (on another protocol) | in the result only | yes, result is the existential | | `mutating func save(_ entity: Entity)` | as a parameter | no | | `static func == (lhs: borrowing Self, rhs: borrowing Self) -> Bool` | as parameters | no | A result is safe because whatever comes out can be described by a supertype: the CHANGELOG says such results are type-erased to the associated type's **upper bound**, another existential with the same constraints. With `associatedtype Entity: Identifiable`, `find(id:)` on the box returns `(any Identifiable)?`. A parameter is unsafe because the box would have to accept a value of a type it cannot name. The diagnostic for the unsafe case is precise: ```plaintext error: member 'save' cannot be used on value of type 'any Repository'; consider using a generic constraint instead ``` For `Equatable` it reads "binary operator '==' cannot be applied to two 'any Equatable' operands". ## Working with the restriction today 1. **Prefer a generic constraint** where one concrete conformer flows through the code. It keeps every requirement and lets the optimizer specialize. 2. **Constrain the associated type** when the protocol declares it as primary: `any Repository<User>` fixes `Entity`, so `save(_:)` with a `User` becomes legal. That syntax is covered with primary associated types. 3. **Pass the box to a generic function** when you must start from an existential; Swift 5.7 also opens existentials implicitly at such calls, which the material on opaque and existential types covers. 4. **Keep heterogeneous storage honest**: an array of `any Repository` can only offer what every repository offers with its entity type hidden. The short version for an interview: it was never that such protocols were broken as types; the compiler could not give `Entity` or `Self` a meaning on a value whose concrete type is hidden, and today that limit applies member by member instead of to the whole protocol.

  • What does `find(id:)` return when called on an `any Repository` whose `Entity` is constrained to `Identifiable`?
    An existential: the result is erased to the associated type's upper bound, so `Entity?` becomes `(any Identifiable)?`. With an unconstrained `Entity` the upper bound is `Any`, so the call returns `Any?`. You get a value, but not its concrete type.
  • Why can't you compare two `any Equatable` values with `==` in Swift?
    `Equatable`'s `==` takes two operands of type `Self`, which is a parameter position. Two boxes may hold different types, an `Int` and a `String`, so the compiler rejects the call with "binary operator '==' cannot be applied to two 'any Equatable' operands". Compare inside generic code, or cast to a concrete type first.
  • Is writing a bare protocol name such as `Repository` as a type still an error in Swift 6.4?
    No, it is a warning. Swift 5.7 required `any` for protocols with associated types or `Self` requirements, but since Swift 6.1 the compiler only warns "use of protocol 'Repository' as a type must be written 'any Repository'; this will be an error in a future Swift language mode". Writing `any` is still the expected spelling.

  • Swift still forbids any protocol with an associated type from being used as a type.
  • On an any Repository every requirement is callable; Entity simply becomes Any.
  • The old restriction existed because existential boxes were too slow, not unsound.
  • Methods returning Self can never be called through an existential.
  • Equatable values boxed as any Equatable can be compared with == directly.

Assumes Swift 6.4; protocols with associated types or Self requirements became usable as any types in Swift 5.7 (SE-0309), and the missing-any error became a warning in Swift 6.1.