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 ...
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.