Why must struct methods that modify properties be marked `mutating`?

iOS interview question for Intermediate practice.

Answer

In Swift, structs are value types. When you pass a struct to a function, a copy is made. Any modifications within the function only affect that copy, leaving the original struct unchanged. To modify the original struct's properties, you must explicitly declare the method as mutating. This signals to the compiler that the method intends to change the struct's internal state. Here's an example: swift struct Point { var x: Int var y: Int mutating func moveBy(dx: Int, dy: Int) { x += dx y += dy } } var p = Point(x: 1, y: 2) p.moveBy(dx: 3, dy: 4) print(p) // Output: Point(x: 4, y: 6) In this example, moveBy modifies the x and y properties. Without mutating, this would result in a compiler error. The compiler enforces this rule to ensure that code behaves predictably, particularly when working with immutable data structures. Best Practices: Always use mutating when a struct method modifies its properties. Consider whether a struct should be a struct (value type) or a class (reference type) based on whether its state needs to be mutable. If you find yourself frequently needing mutating methods, a class might be a more suitable choice. Clearly document the side effects of mutating methods in your code comments.

Explanation

Swift's mutating keyword is a powerful feature that helps enforce immutability and prevents unintended side effects when working with value types.

Related Questions