Immutable value only has mutating members
A struct
is considered a value type, so it’s immutable by default. If you want to change it using a method, you have to declare the method mutating
. Quoting the Swift book:
Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.
You can opt in to this behavior by placing the
mutating
keyword before thefunc
keyword for that method.