Inside a Swift `mutating` method, what does assigning a new value to `self` do, and how does an enum use it to change its own case?
answer
- replace the whole value
- write-back when the method ends
- works even with let properties
- an enum swaps its case
basics
~20 sAssigning to self in a mutating method replaces the entire value with a new one, which is written back to the caller's variable when the method ends. Enums use it to move to a different case, rebuilding any associated values.
solid answer
~40 sA `mutating` method may assign a completely new instance to `self`, and that instance replaces the caller's value when the method ends. For a struct, `self = Version(major: major, minor: minor + 1)` is legal even when `major` and `minor` are `let` properties, because you replace the whole value rather than writing one constant property. For an enum it is how a mutating method changes the value: an enum cannot have stored instance properties, so `mutating func advance()` switches over `self` and assigns the next case, building new associated values such as `.running(progress: progress + step)`. In a class you cannot do this: `self` is an immutable reference there, and `self = …` fails with "cannot assign to value: 'self' is immutable".
code
swift · 34 linesenum Download {
case idle
case running(progress: Double)
case finished
mutating func advance(by step: Double) {
switch self {
case .idle:
self = .running(progress: step)
case .running(let progress) where progress + step >= 1.0:
self = .finished
case .running(let progress):
self = .running(progress: progress + step)
case .finished:
break
}
}
}
struct Version {
let major: Int
let minor: Int
mutating func bumpMinor() {
self = Version(major: major, minor: minor + 1) // legal: replaces the whole value
}
}
var download = Download.idle
download.advance(by: 0.6)
download.advance(by: 0.6)
var version = Version(major: 2, minor: 3)
version.bumpMinor()
print(download, version.minor) // finished 4go deeper
Recall that a mutating method may write self = newValue, and that this is how an enum method switches to a different case.
Explain the write-back: the new value replaces the caller's variable when the method ends, and why this works even when the struct's stored properties are let.
Use self-assignment deliberately: reset methods that stay correct as properties are added, and enum state machines whose transitions all live in one exhaustive switch.
Weigh immutable-property structs replaced wholesale against var-property structs mutated in place: the first makes invariants easier to keep, the second reads more naturally for large values.
## Two ways a mutating method can change a value A `mutating` method on a structure or enumeration has write access to `self` for the duration of the call. It can use that access in two ways: - **Change individual stored properties**, such as `count += 1` on a `var` property. - **Assign a completely new value to `self`**, replacing the whole instance at once. The Swift book describes both: the method can mutate its properties, and it can also assign a completely new instance to its implicit `self` property, which will replace the existing one when the method ends. From the caller's point of view the two are indistinguishable — after the call, the variable holds the new value. ## Replacing a struct whose properties are constants Assigning to `self` is the tool for types whose stored properties are declared with `let`. You cannot write `minor += 1` when `minor` is a `let` — the compiler reports `left side of mutating operator isn't mutable: 'minor' is a 'let' constant`. But a mutating method can still build a replacement: ```swift struct Version { let major: Int let minor: Int mutating func bumpMinor() { self = Version(major: major, minor: minor + 1) } } ``` This is not a loophole. `let` on a property means that property never changes **within one value**; it says nothing about whether the variable holding the value may be given a different value. A caller with `var version` could write `version = Version(...)` directly; the mutating method just packages that assignment behind a name. The call still needs a `var`: a `let version` rejects `bumpMinor()` like any other mutating call. ## Enums change state by assigning a new case Enumerations cannot declare stored instance properties, so a mutating method on an enum has nothing to change piecemeal. The way it changes state is to assign a different case to `self`. This makes enums a natural fit for small state machines: 1. `switch self` to find the current case and bind its associated values. 2. Compute the next state. 3. Assign it: `self = .running(progress: progress + step)` or `self = .finished`. Associated values are rebuilt, not edited: to change `progress`, the method binds the old payload and assigns a new `.running` case carrying the new number. A `case` that should leave the state unchanged simply does nothing (`break`). ## When the new value becomes visible - **Inside the method**, the assignment takes effect immediately: code after `self = …` reads the new value's properties. - **For the caller**, the result is written back when the method ends. This matches the model Swift uses for `inout` parameters, **copy-in copy-out**: the value is copied in, the copy is modified, and the copy is assigned back on return. As an optimization the compiler may operate on the caller's memory directly, but code must not depend on which happens. - **The caller sees one finished value.** However many properties the method changed, and whether it assigned `self` once or several times, the caller's variable ends up holding the final value; the method has exclusive access to it for the whole call, so any other access to that variable during the call is an exclusivity violation rather than a peek at a half-updated value. ## Value types versus classes | | Struct | Enum | Class | |---|---|---|---| | Assign `self` in a mutating method | yes | yes | not applicable: `mutating` is rejected | | Assign `self` in an ordinary method | no: `self` is immutable | no | no: `cannot assign to value: 'self' is immutable` | | Typical use | replace a value with `let` properties, reset to defaults | move to another case | — | A class instance is reached through a reference, and `self` inside a class method is that reference — a constant. Replacing the object would mean changing every reference that points to it, which no method can do. A class changes its state by assigning its own `var` properties instead. ## Common uses - **Reset to defaults:** `mutating func reset() { self = Counter() }` is shorter and safer than zeroing each property by hand, because a newly added property is reset too. - **Normalising a value:** a `mutating func normalize()` can compute a canonical form and assign it in one step. - **State machines:** an enum's `next()` or `advance(by:)` method moves through its cases, keeping every transition in one `switch` that the compiler checks for exhaustiveness.
- Why is `self = Version(major: major, minor: minor + 1)` allowed when `minor` is a `let` property?`let` on a property means it never changes within one value. Assigning to `self` does not change that property; it replaces the whole value with a different one, exactly as `version = Version(...)` would at the call site. The caller still needs a `var`, so a `let version` cannot call the method.
- Inside the mutating method, does code after `self = .finished` see the old case or the new one?The new one. The assignment takes effect immediately inside the method body; only the write-back to the caller's variable waits until the method returns. A `switch self` placed after the assignment would match `.finished`.
- Says assigning to self is only possible inside an initializer
- Believes a class method can replace its own instance with self = Other()
- Thinks an enum method can edit an associated value in place
- Claims let properties make a struct impossible to change through any method
- Says the caller sees each property change one by one during the call