Mutating and self Reassignment
Replace self entirely from a mutating method.
Reassigning self
Inside a mutating method you may assign a brand-new value to self, replacing the entire instance.
struct Point {
var x = 0
var y = 0
mutating func reset() {
self = Point(x: 0, y: 0)
}
}
var p = Point(x: 3, y: 4)
p.reset()
print(p.x, p.y)Why Reassign self
Reassigning self is handy when the new state is easiest to express as a fresh instance rather than editing fields one by one.
struct Vector {
var dx: Int
var dy: Int
mutating func negate() {
self = Vector(dx: -dx, dy: -dy)
}
}
var v = Vector(dx: 2, dy: -3)
v.negate()
print(v.dx, v.dy)All lessons in this course
- Value Types and Immutability
- The mutating Keyword
- Mutating and self Reassignment
- Non-mutating Alternatives