In Swift, the mutating keyword is used in struct and enum definitions to indicate that a method will modify (or "mutate") the instance it belongs to. Unlike classes, structs and enums are value types, meaning they are copied when assigned to a new variable or passed to a function. By default, methods in structs and enums cannot modify instance properties. This is where mutating comes in, allowing methods in these types to modify their properties.
When to Use mutating in Swift
Use mutating when defining a method in a struct or enum that changes one or more of its properties. Without this keyword, any attempt to change properties inside a method will result in a compile-time error.
Example of mutating in a Struct
Here’s an example using a simple Point struct with a move method to change the x and y coordinates:
struct Point {
var x: Int
var y: Int
mutating func move(byX deltaX: Int, byY deltaY: Int) {
x += deltaX
y += deltaY
}
}
var point = Point(x: 2, y: 3)
point.move(byX: 3, byY: 4)
print(point) // Outputs: Point(x: 5, y: 7)
In this example, the move method modifies the x and y properties of Point, so it is marked as mutating.
Be the first to comment