SWIFT : Use of mutating function in Structs
Swift programmers developed Structs in such a way that properties of it can not be modified within Struct methods. For example, Check the code given below :
On executing the above code we get an error because we are trying to assign a new value to the property population of the Struct City. By default Structs properties can’t be mutated inside its own methods. This is how Apple Developers have built it, so that the Structs will have a static nature by default.
How do we solve it? What’s the alternative?
Mutating Keyword :
Declaring function as mutating inside Struct allows us to alter properties in Structs.
Line No : 5, of the above code changes to like this,
Now we can assign the value of the newpopulation to property population to within the scope of the method.
If we use let instead of var for Struct objects, then we can’t mutate the value of any properties, Also this is the reason why we get an error when we try to invoke mutating function using let instance. So it is better to use var whenever you are changing value of a property.
Would love to hear your comments and thoughts…..