In Swift, structures (struct) are value types by default: when copying an instance of a structure, an independent copy is created. However, unlike classes, the methods of a structure cannot modify self and its properties without direct permission from the compiler. In earlier versions of the C and C++ languages, structures were always mutable, leading to unexpected side effects. Swift enhances safety by requiring methods that alter the state of the structure to be explicitly marked with the keyword mutating.
The problem arises when a method is needed to change the properties of the structure, but it is declared as a regular method, and the compiler does not allow this. Without mutating, it is not possible to change self or its properties.
The solution is to declare such methods with the mutating keyword, which gives the compiler a signal to allow the modification of self and nested properties.
Code example:
struct Counter { var value = 0 mutating func increment() { value += 1 } // This method WILL not compile if mutating is removed } var counter = Counter() counter.increment() // value is now 1
Key features:
1. Can you call mutating methods on a structure declared with let?
No, you cannot. Constant let values of structures cannot be modified, even with mutating methods.
let counter = Counter() counter.increment() // Compilation error
2. Can nested class properties within a structure be modified inside a structure's mutating method?
Yes, if the property of the structure is a reference type (such as a class), its internal properties can be changed without mutating, but the structure as a whole can only be modified through mutating.
class State { var value = 0 } struct Wrapper { var state = State() mutating func change() { state.value += 1 } }
3. Can you change only a computed property within a method without mutating?
No. If a computed property has a set, changing its value within the method still requires mutating.
In the project, a simple counter is implemented with a structure, but the developer forgot to mark the method as mutating. The tests do not pass because the value does not change.
Pros:
Cons:
The methods in the structure are marked with mutating, the tests pass, and the changes are updated correctly. The code is clear to all team members.
Pros:
Cons: