November 2016
Intermediate to advanced
480 pages
14h 42m
English
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 ...
Read now
Unlock full access