← Back to Swift Course | Chapter 12: Generics & Advanced Types | Lesson 4 of 7

Associated Types

An associated type is like a placeholder name a protocol uses for "some type I need, but I'll let each conformer decide exactly what it is."

Declaring a Protocol with an Associated Type

associatedtype lets a protocol describe a requirement in terms of a placeholder type, which each conforming type specifies concretely.

Example: Declaring a Protocol with an Associated Type

markup
protocol Container {
    associatedtype Item
    mutating func add(_ item: Item)
    var count: Int { get }
}
struct IntContainer: Container {
    var items: [Int] = []
    mutating func add(_ item: Int) {
        items.append(item)
    }
    var count: Int {
        return items.count
    }
}
var container = IntContainer()
container.add(5)
container.add(10)
print("Count: \(container.count)")

Swift Infers the Associated Type

Swift automatically infers the concrete type used for Item just from how the conforming type implements add(_:), without needing an explicit typealias.

Example: Swift Infers the Associated Type

markup
protocol Container {
    associatedtype Item
    mutating func add(_ item: Item)
}
struct StringContainer: Container {
    var items: [String] = []
    mutating func add(_ item: String) {
        items.append(item)
    }
}
var container = StringContainer()
container.add("hello")
print(container.items)
Common Mistakes
  1. Confusing an associated type (a placeholder used inside a protocol) with a generic function's placeholder (used in a function or type declaration).
  2. Trying to use a protocol with an associated type as a plain variable's type directly (e.g. var x: Container); it must be used generically or with some/any.
  3. Forgetting Swift can often infer the concrete associated type automatically from how the conforming type implements the protocol's requirements.
Chapter Summary
  • associatedtype declares a placeholder type used within a protocol's requirements.
  • Each conforming type fills in the associated type with a concrete type of its choosing.
  • Protocols with associated types can't be used as plain standalone variable types without some or any.
  • Associated types make protocols flexible enough to describe generic containers and behaviors.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.