Mutating methods in Swift

Vinod Jagtap
Apr 12, 2021

Sometimes we need to change the properties of struct or enum from within its instance methods but the compiler gives an error.

So why this happens only with structs and enums?
The answer is structs and enums are value types. By default, the properties of value type can’t be modified from within instance methods.
So to change the properties, we need to mark the method as mutating.
This modifies the properties at the end of the method.

Mutating methods can assign an entirely new instance to the implicit self property.

Thanks for reading.

--

--