Mutating Methods and Copy-on-Write Semantics
Why mutating is required and how Swift's COW optimization works.
Welcome
Struct methods that modify stored properties must be marked `mutating`. Swift also uses Copy-on-Write (COW) to make value semantics efficient.
mutating Keyword
```swift
struct Counter {
var count = 0
mutating func increment() { count += 1 }
mutating func reset() { count = 0 }
}
var c = Counter()
c.increment() // count = 1
```
Without `mutating`, the compiler rejects methods that change `self`.
All lessons in this course
- Memberwise Initializers and Custom Inits
- Stored Properties and Property Observers
- Computed Properties in Structs
- Mutating Methods and Copy-on-Write Semantics