Mutating Methods
A mutating method is a special kind of action a struct can perform that's allowed to change its own properties.
Syntax
struct TypeName {
var property: Type
mutating func methodName() {
property = newValue
}
}
var instance = TypeName(property: value) // must be var
instance.methodName()
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
// Define a struct `Counter`
struct Counter {
// Declare a mutable variable `count`, initialized to `0`
var count = 0
mutating func increment() {
count += 1
}
}
// Declare a mutable variable `counter`, initialized to `Counter()`
var counter = Counter()
counter.increment()
counter.increment()
// Print "Count: \(counter.count)" to the console
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
// Define a struct `Switch`
struct Switch {
// Declare a mutable variable `isOn`, initialized to `false`
var isOn = false
mutating func toggle() {
isOn.toggle()
}
}
// Declare a mutable variable `lightSwitch`, initialized to `Switch()`
var lightSwitch = Switch()
lightSwitch.toggle()
// Print "Is on: \(lightSwitch.isOn)" to the console
print("Is on: \(lightSwitch.isOn)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: