O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. The two protocols you will use are IteratorProtocol and Sequence, which together allow you to make your own types that can be iterated over in for-in loops. First, the IteratorProtocol protocol:

protocol IteratorProtocol {
    associatedtype Element

    mutating func next() -> Element?
}

IteratorProtocol requires a single mutating method, next(), which returns ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required