December 2015
Intermediate to advanced
400 pages
13h 3m
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. 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 ...
Read now
Unlock full access