Mutating a Struct
suggest changeA method of a struct that change the value of the struct itself must be prefixed with the mutating
keyword
struct Counter {
private var value = 0
mutating func next() {
value += 1
}
}
When you can use mutating methods
The mutating
methods are only available on struct values inside variables.
var counter = Counter()
counter.next()
When you can NOT use mutating methods
On the other hand, mutating
methods are NOT available on struct values inside constants
let counter = Counter()
counter.next()
// error: cannot use mutating member on immutable value: 'counter' is a 'let' constant
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents