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
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var counter = Counter()
counter.increment()
counter.increment()
print("Count: \(counter.count)")
Login to try C/C++/Java/PHP code in the editor
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
struct Switch {
var isOn = false
mutating func toggle() {
isOn.toggle()
}
}
var lightSwitch = Switch()
lightSwitch.toggle()
print("Is on: \(lightSwitch.isOn)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
mutatingkeyword on a struct method that modifiesselfor any of its properties, causing a compile error. - Trying to call a
mutatingmethod on a struct instance declared withlet; onlyvarinstances allow mutation. - Adding
mutatingto 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
mutatingbeforefunc. - A
mutatingmethod can only be called on an instance stored in avar, not alet. - Classes never need
mutatingsince their methods can always change properties. - A mutating method can even reassign
selfentirely to a new instance of the same struct.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: