0Pricing
Swift Academy · Lesson

Constraining Associated Types

Limit associated types in generic contexts.

Associated Types Recap

A protocol can declare an associated type with associatedtype, a placeholder a conforming type fills in. Element in a container protocol is the classic example.

protocol Container {
    associatedtype Item
    var count: Int { get }
    func item(at i: Int) -> Item
}

Conforming with a Concrete Type

A conforming type fixes the associated type, often inferred from how it is used.

protocol Container {
    associatedtype Item
    func item(at i: Int) -> Item
}
struct IntBox: Container {
    let values: [Int]
    func item(at i: Int) -> Int { values[i] }
}
print(IntBox(values: [10, 20]).item(at: 1))

All lessons in this course

  1. Type Parameter Constraints
  2. where Clauses on Functions
  3. Constraining Associated Types
  4. Generic Subscripts and Extensions
← Back to Swift Academy