0Pricing
Swift Academy · Lesson

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)

All lessons in this course

  1. Value Types and Immutability
  2. The mutating Keyword
  3. Mutating and self Reassignment
  4. Non-mutating Alternatives
← Back to Swift Academy