Associated Type Protocols

Now that you know that types, functions, and methods can be made generic, it is natural to ask whether protocols can be made generic as well. The answer is no. However, protocols support a similar and related feature: associated types.

Let’s explore protocols with associated types by examining a couple of protocols defined by the Swift standard library. First, the GeneratorType protocol:

protocol GeneratorType {
    typealias Element

    mutating func next() -> Element?
}

The GeneratorType protocol requires a single mutating method, next(), which returns a value of type Element?. The purpose of GeneratorType is that you can call next repeatedly and it generates new values each time. If the generator is ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.