How to modify value types within instance methods in Swift?

Properties of value types such as Structures and enumerations cannot be modified within instance methods. In order to modify their property, we need to add the keyword mutating before the instance method. Now the method can mutate(change) the properties and write back the changes to the original structure at the end of the method. 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. We cannot call mutating method on constant of struct type because its properties cannot be changed even if they are variable properties.

Leave a Reply