November 2016
Intermediate to advanced
480 pages
14h 42m
English
Recall from Chapter 14 and Chapter 15 that methods on value types (structs and enums) cannot modify self unless the method is marked as mutating.
Methods in protocols default to nonmutating.
In the Lightbulb enum from Chapter 14, the toggle() method was mutating.
enum Lightbulb {
case on
case off
...
mutating func toggle() {
switch self {
case .on:
self = .off
case .off:
self = .on
}
}
}
Suppose you want to define in a protocol that an instance is “toggleable”:
protocol Toggleable {
func toggle()
}
Declaring that Lightbulb conforms to Toggleable would result in a compiler error. The message you get includes a note that explains the problem:
error: type 'Lightbulb' does not conform to protocol 'Toggleable' ...
Read now
Unlock full access