Non-mutating Alternatives
Return new values instead of mutating in place.
Return Instead of Mutate
Instead of changing an instance in place, a non-mutating method can return a brand-new value with the change applied.
struct Counter {
var value: Int
func incremented() -> Counter {
return Counter(value: value + 1)
}
}
let c = Counter(value: 0)
let next = c.incremented()
print(c.value, next.value)Original Stays Unchanged
Because nothing is mutated, the original value is preserved and a new value is produced.
struct Vector {
var x: Int
var y: Int
func scaled(by factor: Int) -> Vector {
return Vector(x: x * factor, y: y * factor)
}
}
let v = Vector(x: 2, y: 3)
let big = v.scaled(by: 10)
print(v.x, v.y, big.x, big.y)All lessons in this course
- Value Types and Immutability
- The mutating Keyword
- Mutating and self Reassignment
- Non-mutating Alternatives