Updated 29 April 2021
In mutable value may be intialised and it get changed any time, while in case of immutable value is intialised once and never changed(like constants values). In swift, classes are reference type and every change in a reference type will modify the value allocated in that place of memory or reference whereas structures and enumerations are value types and that means that every change on them will just modify that value. The properties of value types cannot be modified within its instance methods by default. So, for modification the properties of it, you have to use the “mutating” keyword in the instance method.
From mutating keyword, struct or enum methods have ability to change the values of the properties and change it as according you want. Let discuus with the examples for struct and classes:
Mutating Example for Struct
Let’s create the simple struct as:
123 struct ForStruct {private var data : String?}
Now intialise the struct.
1 var structObj = ForSruct()
When you are trying to decalre the value in struct then it will display the error.
To resolve this error we have to use mutating method in the struct as:
12345678 struct ForSruct{private var data : String?public mutating func addNew(_ new: String){self.data = new}}
And we declare it as,
123 var structObj = ForSruct()structObj.addNew("Value")Now it will work fine.
Mutating Example for Class
Lets create the class with mutating method as:
12345678 class ForClass{private var classData: String?public mutating func addNew(_ new: String){self.classData = new}}
But mutating methods shows error with the class.
Now remove it from the method and it will start working normaly.
12345678 class ForClass{private var classData: String?public func addNew(_ new: String){self.classData = new}}You can change any value property on a even when the class itself is created as a constant.
Conclusion
I hope this blog will help you in understanding the behaviour of mutating keyword with struct and class, if you have any comments, questions, or recommendations, feel free to post them in the comment section below!
For other blogs, please click here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.