Mutating a Struct

suggest change

A 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents