What does the Swift mutating keyword mean?
What does the Swift mutating keyword mean?
The mutating keyword in Swift is used to indicate that a method can modify the properties of a value type, such as a struct or an enum. By default, methods on value types cannot change the instance's properties. The mutating keyword explicitly allows the method to alter the instance's state.
mutating Keyword:Value Types: In Swift, structs and enums are value types, meaning they are copied when assigned to a new variable or passed to a function. This immutability by default ensures that the original instance remains unchanged unless explicitly allowed to mutate.
Method Declaration: When you define a method within a struct or enum that modifies any of its properties, you must prefix the method with the mutating keyword. This informs the compiler and the caller that the method will change the instance's state.
Usage Example:
struct Person {
var name: String
mutating func changeName(to newName: String) {
name = newName
}
}
var person = Person(name: "Alice")
person.changeName(to: "Bob")
print(person.name) // Outputs: Bob
Reassigning self: Within a mutating method, you can also reassign self to a new instance, effectively replacing the entire instance with a new one.
struct Point {
var x: Int
var y: Int
mutating func moveTo(x newX: Int, y newY: Int) {
self = Point(x: newX, y: newY)
}
}
Protocols: When a protocol requires a method that modifies the instance, the method must be marked as mutating in the protocol definition. Classes conforming to such protocols do not need to use the mutating keyword because classes are reference types and inherently mutable.
protocol Resettable {
mutating func reset()
}
struct Counter: Resettable {
var count: Int = 0
mutating func reset() {
count = 0
}
}
Constants and Variables: You cannot call a mutating method on a constant instance of a struct or enum. The instance must be a variable.
let fixedPoint = Point(x: 0, y: 0)
// fixedPoint.moveTo(x: 10, y: 10) ...
middle