Redeem Now
Read More
Read now

Mutating in Swift

Save

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:

 

Now intialise the struct.

 

When you are trying to decalre the value in struct then it will display the error.

Struct Error

 

To resolve this error we have to use mutating method in the struct as:

 

And we declare it as,

Now it will work fine.

 

Mutating Example for Class

Lets create the class with mutating method as:

 

But mutating methods shows error with the class.

Class Error

 

Now remove it from the method and it will start working normaly.

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.

 

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close