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