Swift: Understanding Mutating Functions in Two Minutes

If you have ever tried using the mutating keyword in your class methods in Swift, the compiler will definitely yell at you because you are doing something wrong.

In swift, classes are reference type whereas structures and enumerations are value types. The properties of value types cannot be modified within its instance methods by default. In order to modify the properties of a value type, you have to use the mutating keyword in the instance method. With this keyword, your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.

Below is a simple implementation of Stack in Swift that illustrates the use of mutating functions.

I believe this is pretty straight forward to understand. If, however you need any clarification or questions, leave me a comment below and I will get it answered. Thanks for reading.