Associated Types

Now that you know that types and functions (including 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 associated types by examining a couple of protocols defined by the Swift standard library. The two protocols you will examine are IteratorProtocol and Sequence, which together allow you to make your own types that can be iterated over in for-in loops.

These protocols already exist in the Swift standard library, so you should not type them in. First, have a look at the definition of IteratorProtocol:

 protocol IteratorProtocol { associatedtype Element mutating func ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.