Mutating in Swift

Updated 29 April 2021

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.

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home