Google News
logo
Swift - Interview Questions
What is the use of the "mutating" keyword in ios Swift?
Ios Swift structs are immutable since they are of the value type. Other variables, for example, cannot modify the values of structure at any point in time. Only the "mutating" keyword is necessary to change the values of self variables within the function of the structure. Let us take the following code snippet for example:
struct demoStruct {
   var foo: String = "Initial String"
   func transformString() {
       foo = "Transformed String". 
//The above results in a compile time error: Cannot assign to property: 'self' is immutable. 
//We need to mark the method 'mutating' to make 'self' mutable.
   }
}
 
We get a compile-time error when we try to alter the value of variable "foo" inside a function declared in the struct itself.
 
As a result, we will need to create a mutating function to update the value inside the structure. As a result, the correct code is:
struct demoStruct {
   var foo: String = "Initial String"
   mutating func transformString() {
       foo = "Transformed String". 
   }
}
Advertisement