Some protocols may have methods that mutate the object members or properties. Consider the following protocol:
protocol Incrementing {
func increment() -> Int
}
The Incrementing protocol requires the implementation of a single method, increment() -> Int, which returns the current value after the increment. This protocol may be used whenever we need to count linearly. It also suggests that it increments a local counter:
struct Counter: Incrementing {
private var value: Int = 0
func increment() -> Int {
value += 1
return value
}
}
This implementation will not compile and will emit the following error:
Left side of mutating operator isn't mutable: 'self' is immutable
This error is emitted because the increment() function is not marked mutable on the structure. However, we have also to add the mutating keyword to the protocol; otherwise, the protocol would still be immutable by default and the structure is not conforming.
protocol Incrementing {
mutating func increment() -> Int
}
struct Counter: Incrementing {
private var value: Int = 0
mutating func increment() -> Int {
value += 1
return value
}
}
var counter = Counter()
assert(counter.increment() == 1)
assert(counter.increment() == 2)