What if you could change a value type's data directly without juggling copies everywhere?
Why Mutating methods for value types in Swift? - Purpose & Use Cases
Imagine you have a simple box that holds a number. You want to change the number inside the box. But every time you try to change it, you realize the box is a copy, not the original. So your changes don't stick.
When you try to change values inside a copy, your changes only affect that copy, not the original. This means you have to write extra code to replace the original with the changed copy. It's slow, confusing, and easy to make mistakes.
Mutating methods let you change the value inside the original box directly. By marking a method as mutating, Swift knows it can safely update the value type itself, making your code simpler and clearer.
struct Box {
var number: Int
func increase() -> Box {
return Box(number: number + 1)
}
}
var box = Box(number: 5)
box = box.increase()struct Box {
var number: Int
mutating func increase() {
number += 1
}
}
var box = Box(number: 5)
box.increase()It enables you to write clean, direct code that changes value types without extra copying or confusion.
Think of a game character's health stored as a value type. Mutating methods let you easily update health points directly when the character takes damage or heals.
Value types are copied when changed, so direct updates need special handling.
Mutating methods allow changing the original value type inside its own methods.
This makes code simpler, safer, and easier to understand.