← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 9 of 9

Mutating Methods

A mutating method is a special kind of action a struct can perform that's allowed to change its own properties.

Declaring a Mutating Method

Marking a method mutating allows it to change the struct's own stored properties, which is otherwise disallowed since structs are value types.

Example: Declaring a Mutating Method

markup
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}
var counter = Counter()
counter.increment()
counter.increment()
print("Count: \(counter.count)")

Mutating Methods Require var Instances

A mutating method can only be called on an instance declared with var, since a let instance is fully immutable.

Note: If lightSwitch were declared with let instead of var, calling .toggle() would fail to compile.

Example: Mutating Methods Require var Instances

markup
struct Switch {
    var isOn = false
    mutating func toggle() {
        isOn.toggle()
    }
}
var lightSwitch = Switch()
lightSwitch.toggle()
print("Is on: \(lightSwitch.isOn)")
Common Mistakes
  1. Forgetting the mutating keyword on a struct method that modifies self or any of its properties, causing a compile error.
  2. Trying to call a mutating method on a struct instance declared with let; only var instances allow mutation.
  3. Adding mutating to a class method by mistake; the keyword is only meaningful for structs and enums, not classes.
Chapter Summary
  • Struct methods that modify properties must be marked mutating before func.
  • A mutating method can only be called on an instance stored in a var, not a let.
  • Classes never need mutating since their methods can always change properties.
  • A mutating method can even reassign self entirely to a new instance of the same struct.
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.