The mutating Keyword
Write methods that modify struct and enum state.
Methods Cannot Mutate by Default
An instance method of a struct cannot change the struct's stored properties unless it is marked mutating.
struct Counter {
var value = 0
mutating func increment() {
value += 1
}
}
var c = Counter()
c.increment()
print(c.value)Why mutating Is Needed
Because structs are value types, the compiler requires you to opt in to mutation so the change is explicit.
struct Bank {
var balance = 0
mutating func deposit(_ amount: Int) {
balance += amount
}
}
var b = Bank()
b.deposit(50)
print(b.balance)