skip to content

What does declaring a primary associated type, as in Swift's `protocol Repository<Entity>`, let callers write that a plain `associatedtype` does not?

level: seniorimportance: should knowfreq 30%

answer

  1. angle brackets on the protocol name
  2. shorthand for a same-type requirement
  3. Collection<Element> in the standard library
  4. constrained some and any

basics

~20 s

It lets the protocol take type arguments: Repository<User> means conforms to Repository with Entity == User. The shorthand works in generic constraints and extensions, and it is the only way to constrain Entity on some or any types.

solid answer

~40 s

Since Swift 5.7 (SE-0346) a protocol can list **primary associated types** in angle brackets after its name, `protocol Repository<Entity>`, alongside the usual `associatedtype Entity`. Then `Repository<User>` is shorthand for a conformance plus a same-type requirement: `<R: Repository<User>>` means `R: Repository, R.Entity == User`, and `extension Repository<User>` means `extension Repository where Entity == User`. The real gain is where no `where` clause can go: `some Repository<User>` as a parameter or result, and `any Repository<User>` (SE-0353), on which `save(_:)` with a `User` is legal again. The standard library uses it for `Sequence<Element>`, `Collection<Element>` and `Identifiable<ID>`. Callers must supply every primary associated type, so SE-0358 advises declaring at most one, chosen as the type users constrain most.

code

swift · 31 lines
swift
struct User: Identifiable { let id: Int; var name: String }

// Entity is the primary associated type: it may be written in angle brackets.
protocol Repository<Entity> {
    associatedtype Entity: Identifiable
    func find(id: Entity.ID) -> Entity?
    mutating func save(_ entity: Entity)
}

struct InMemoryRepository<Entity: Identifiable>: Repository {
    private var storage: [Entity.ID: Entity] = [:]
    func find(id: Entity.ID) -> Entity? { storage[id] }
    mutating func save(_ entity: Entity) { storage[entity.id] = entity }
}

// Shorthand for <R: Repository> ... where R.Entity == User
func rename(_ id: Int, to name: String, in repo: inout some Repository<User>) {
    guard var user = repo.find(id: id) else { return }
    user.name = name
    repo.save(user)
}

// Shorthand for extension Repository where Entity == User
extension Repository<User> {
    func displayName(of id: Int) -> String { find(id: id)?.name ?? "unknown" }
}

var users = InMemoryRepository<User>()
users.save(User(id: 1, name: "ada"))
rename(1, to: "Ada", in: &users)
print(users.displayName(of: 1))   // Prints "Ada"

go deeper

for a junior

Recall that Collection<Int> style angle brackets work because the protocol declares a primary associated type, Element.

for a middle

Explain the shorthand: Repository<User> in a constraint or extension equals a conformance plus Entity == User, and show the long form.

for a senior

Show what only primary associated types express, constrained some results and any Repository<User>, and the errors when the list is missing or incomplete.

for a principal

Choose a shared protocol's primary associated types knowing the list is permanent API: pick what callers constrain, usually one, or none.

## Declaring a primary associated type A **primary associated type** is an associated type the protocol promotes into an angle-bracket list after its name: ```swift protocol Repository<Entity> { associatedtype Entity: Identifiable func find(id: Entity.ID) -> Entity? mutating func save(_ entity: Entity) } ``` The `associatedtype Entity` declaration is still required; the list only marks which associated types callers may constrain with angle brackets. A protocol can list several, as in `protocol Graph<Vertex, Edge>`. Conformers are unaffected: they still choose `Entity` by inference, a typealias, a nested type or a generic parameter, exactly as before. The feature arrived in Swift 5.7 with SE-0346, and SE-0358 annotated the standard library in the same release: `Sequence<Element>`, `Collection<Element>`, `IteratorProtocol<Element>` and `Identifiable<ID>` all declare one. ## What the angle brackets mean `Repository<User>` is **not** a generic protocol in the way `Array<User>` is a generic type. It is shorthand, written wherever a conformance requirement may appear, for "conforms to `Repository` and its `Entity` is `User`": | Shorthand | Equivalent long form | |---|---| | `func f<R: Repository<User>>(_ r: R)` | `func f<R>(_ r: R) where R: Repository, R.Entity == User` | | `extension Repository<User> { ... }` | `extension Repository where Entity == User { ... }` | | `func f(_ r: some Repository<User>)` | `func f<R: Repository>(_ r: R) where R.Entity == User` | ## What only the angle brackets can express For generic functions and extensions the shorthand is convenience. In two places it adds expressivity no `where` clause can provide: - **Constrained opaque result types.** `func makeUserStore() -> some Repository<User>` hides the concrete repository but promises its entity type. Swift's CHANGELOG calls this "new expressivity in Swift 5.7"; there is no `where` clause on an opaque result to write it any other way. - **Constrained existentials.** `any Repository<User>` (SE-0353) is a box that holds any repository *of users*. Because the box now knows `Entity`, `save(_:)` taking a `User` is callable on it, which is impossible on a plain `any Repository`. ```swift func makeUserStore() -> some Repository<User> { InMemoryRepository<User>() } var store: any Repository<User> = InMemoryRepository<User>() store.save(User(id: 2, name: "Grace")) var opaque = makeUserStore() opaque.save(User(id: 3, name: "Linus")) ``` Both calls to `save(_:)` compile. The caller of `makeUserStore()` never learns that the store is an `InMemoryRepository`, so the implementation can later switch to a database-backed type without touching call sites, yet the caller still knows it stores users. The existential `store` can be reassigned to any repository of users at run time. Without a primary associated type, the opaque version could only promise "some repository" and the existential could not accept a `User` at all. Two limits apply. A protocol without a primary list cannot be specialized: the compiler reports "protocol 'Repository' does not have primary associated types that can be constrained". And a caller must constrain **every** primary associated type at once; `some Graph<Int>` against `Graph<Vertex, Edge>` fails with "protocol type 'Graph' specialized with too few type arguments (got 1, but expected 2)". ## Choosing the primary associated type SE-0358 gives guidelines the standard library followed, and they apply to your own protocols: 1. **Pick the type callers constrain most.** Use sites of `Sequence` overwhelmingly constrain `Element`, rarely `Iterator`, so `Element` is primary. 2. **Prefer a type with an obvious relationship.** A good primary reads with a simple preposition: a `Collection` *of* `Int`, an `Identifiable` *by* `String`, a `Repository` *of* `User`. 3. **Usually declare just one.** Because every primary type must be supplied, a second one forces callers back to `where` clauses when they care about only one. 4. **Not every protocol needs one.** If nobody constrains the associated type, leave the list off. The choice is also API: SE-0358 notes that primary associated types cannot be removed or reordered without breaking source compatibility, and adding one to a protocol that already has some is source-breaking too. ## Reading primary associated types in the wild Most developers meet the feature as a reader before they ever declare one: - `func total(_ values: some Collection<Int>) -> Int` accepts an `Array<Int>`, a `Set<Int>`, a range or an array slice, without a generic parameter list. - `let names: any Sequence<String>` stores any sequence of strings behind one type. - `extension Collection<Int>` is the same extension as `extension Collection where Element == Int`. ## Runtime notes Generic code and `some` types compile away. Constrained existentials such as `any Collection<String>` need run-time support for dynamic casts (`is`, `as?`, `as!`) and for use inside generic types such as `Array<any Collection<Int>>`; the CHANGELOG notes these involve additional availability checks, which matters when an app deploys to older OS releases.

  • What does the Swift compiler say if you write `some Repository<User>` for a protocol that declares no primary associated type?
    It rejects it: "protocol 'Repository' does not have primary associated types that can be constrained". The fix is to add `<Entity>` after the protocol name, or to fall back to a generic parameter with `where R.Entity == User`.
  • Why does `Sequence` make `Element` its primary associated type rather than `Iterator`?
    SE-0358 chose the associated type that use sites constrain overwhelmingly more often. Code says "a sequence of `Int`" all the time and almost never constrains the iterator type, so `some Sequence<Int>` reads naturally while an iterator argument would not.
  • Why is it risky to declare two primary associated types on a widely used protocol?
    SE-0346 requires every primary associated type to be supplied, so a caller who cares only about one must abandon the shorthand for a `where` clause. The list is also API: removing or reordering entries, or adding one where some already exist, breaks source compatibility for every client.

  • Repository<User> makes Repository a generic type, just like Array<User>.
  • Any associated type can go in angle brackets without being declared primary.
  • The primary list replaces the associatedtype declarations in the protocol body.
  • A caller may constrain only one of several primary associated types.
  • some Repository<User> and the where-clause form R.Entity == User mean different things.