Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 146 ยท Protocols and Generics

Associated Types

Learn Swift associated types - associatedtype placeholders in protocols, inference, constraints, primary associated types like any Container<Int>, type erasure, and Sequence and Collection examples.

A protocol says what a type can do. Sometimes it also needs to say something about a type that the conforming type chooses. Think of a container: every container holds items, but one holds integers and another holds strings. The protocol cannot name the item type, because it differs from conformer to conformer. It also should not be generic in the way a struct is, because a type does not "pick" a protocol's generic argument; it simply conforms once.

Swift's answer is the associated type. You declare a placeholder inside the protocol with associatedtype, and each conforming type fills it in. This is the machinery behind Sequence, Collection, IteratorProtocol, Identifiable, RawRepresentable and much of the standard library, so understanding it unlocks a lot of Swift.

Declaring an associated type

Here is a small protocol for a container of items. The placeholder is called Item.

Swift A protocol with an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

IntBag never writes typealias Item = Int. The compiler infers the associated type from how the requirements are satisfied: append(_ item: Int) and subscript -> Int both say that Item must be Int. Stack<Element> is generic, so its associated type Item becomes whatever Element is. If you prefer to be explicit, or the compiler cannot infer, you can write typealias Item = Int inside the type.

Inside the protocol, Item is a real type name you can use in requirements: parameters, return values, subscripts and other associated types.

Using the associated type in generic code

A generic function can accept any Container and refer to its Item as C.Item.

Swift Generic functions over a protocol with an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

firstAndLast returns a tuple of C.Item. For numbers that is a pair of Int, for names a pair of String. total adds a same-type constraint: where C.Item == Int says "any container, as long as its items are exactly integers". Calling total(names) would not compile. See Generic Functions for more on where clauses.

Constraining and defaulting an associated type

Just like a generic parameter, an associated type can be constrained, which lets the protocol's own extensions use the capability.

Swift Constraints on an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because Element: Hashable is part of the protocol, every conformer must supply a hashable type, and the extension can safely call Set(elements) and ==. The output is 3 3 for the basket (three different fruits, three apples) and 3 3 for the dice (the faces 6, 1 and 3, and three sixes).

An associated type may also have a default with = Type:

Swift
protocol Scorer {
    associatedtype Score = Int
    func score(of word: String) -> Score
}

A conformer that returns Int from score(of:) does not need to say anything. One that returns Double is inferred as Double. Defaults are rare; reach for them only when almost every conformer uses the same type.

You cannot always use the protocol as a plain type

Before Swift 5.7, a protocol with an associated type could be used only as a generic constraint. Today you can use it as a type if you write any, but there is a limit: the compiler no longer knows what Item is, so anything that takes or returns an Item becomes unusable on the value.

Swift The existential forgets Item (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

anyContainer.count is fine, because Int does not mention the unknown type. anyContainer.append(5) fails, because append needs an Item and the compiler has forgotten what the box holds; the diagnostic is main.swift:15:1: error: member 'append' cannot be used on value of type 'any Container'; consider using a generic constraint instead. There are three ways out, from best to worst: make the function generic (func fill<C: Container>(...)), use a primary associated type so the box is not blind, or erase the type by hand.

Primary associated types

Since Swift 5.7 a protocol can name its most important associated types in angle brackets, like a generic parameter. They are called primary associated types. The standard library does this for Sequence<Element>, Collection<Element>, AsyncSequence<Element, Failure> and others.

Swift Primary associated types in angle brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Writing any Source<Int> pins the associated type to Int, so the compiler knows next() returns Int? even though it does not know which concrete type is inside. That is what makes the array of mixed sources possible. some Source<String> constrains an argument without making shout explicitly generic. The last lines show the same idea with any Sequence<Int>: you can call map and build an array because the element type is known.

Primary associated types are a convenience for the "I only care about this one type" case. The protocol still has all its associated types; the angle brackets just let you constrain them in some and any positions without a where clause. some versus any is the topic of Opaque and Existential Types.

Type erasure

Before primary associated types existed, library authors wrapped a protocol in a struct that stored the behavior in closures and exposed only a generic parameter. This is type erasure, and the names AnySequence, AnyIterator and AnyHashable in the standard library are examples. You may meet it in older code, and it is a good exercise in how the pieces fit.

Swift Writing a type eraser by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

AnyAnimal<String> can hold a Cow or a Goat because both feed on String, and it closes over each animal's eat. A Hamster cannot join the array: its Food is Int, so it can only be AnyAnimal<Int>. With a primary associated type you would declare protocol Animal<Food> and write [any Animal<String>], getting the same result without any hand-written wrapper. Prefer that for new code, and write an eraser only when you need to hide extra details or support older compilers.

Associated types in the standard library

You have already used these protocols. Here is a minimal Sequence of your own, to show how Element and Iterator are filled in.

Swift Conforming to Sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Sequence has two associated types: Iterator (which must conform to IteratorProtocol) and Element. We supplied only makeIterator(), and the compiler worked out Element == Int from the iterator's next() result. The reward is large: map, filter, contains, prefix, sorted and dozens of other methods now work for Countdown, all from the protocol extension on Sequence. This is the "write one small thing, receive many" pattern that makes protocols with associated types so powerful. Collection Protocols shows the next rungs of the ladder.

Common mistakes

  • Treating associatedtype like a generic parameter. A protocol never receives type arguments at conformance time; the conforming type decides. The angle brackets after a protocol name are primary associated types, not independent generics.
  • Using the protocol as an ordinary type and being surprised. any Container forgets its Item. Use a generic function, a primary associated type, or some when you can.
  • Naming clashes. If a conformer is generic over Element and the protocol also has Element, they are separate names that happen to match. Be explicit with typealias Item = Element if the compiler cannot infer.
  • Over-abstracting. If only one type will ever conform, a protocol with an associated type is probably a detour.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does associatedtype Item declare inside a protocol?

    The conforming type picks the concrete type, either with a typealias or through inference from its method signatures.
  2. 2. A struct implements func append(_ item: Int) and subscript(i: Int) -> Int. How is the protocol's Item determined?

    Swift infers associated types from the members that satisfy the requirements. A typealias is only needed when inference is ambiguous.
  3. 3. Why does anyContainer.append(5) fail when anyContainer is any Container?

    The existential hides the concrete type and therefore Item. Members that use Item in a parameter position are unavailable unless a primary associated type fixes it.
  4. 4. What does protocol Source<Item> make possible?

    A primary associated type can be specified in angle brackets at use sites, so you can say which Item is expected.
  5. 5. Which two associated types does Sequence have?

    Sequence declares Element and Iterator; Iterator conforms to IteratorProtocol and yields Elements.

Summary

  • associatedtype declares a placeholder in a protocol that the conforming type fills in, usually by inference.
  • Refer to it as C.Item in generic code and constrain it with where C.Item == Int or Element: Hashable.
  • Protocol extensions can use an associated type's constraints to provide many methods for free.
  • any Protocol forgets associated types; primary associated types (protocol Source<Item>) let you write any Source<Int> and some Source<String>.
  • Type erasure with a wrapper struct is the older workaround; prefer primary associated types in new code.
  • Sequence, Collection and IteratorProtocol are the best-known examples.

Next: Generics