Mutating Keyword in Swift

Javid Museyibli
The Startup
Published in
3 min readJan 2, 2021

--

You probably have come across the mutating keyword in Swift and wonder what is it all about? To define it we need to understand how structs are organized in Swift first.

A struct is a data type that organizes property and methods in a unit. It has almost the same interface as a class with a few subtle differences. For example, once you set up a struct’s properties, it automatically generates memberwise initializers while a classes will not. The other significant difference is that while structs are value types, classes are reference types.

What does this mean? This basically means that when a struct instance is passed around, each time a new copy is created, whereas a class instance would use to the same reference when passed around. Changing a value of a property of class instance will not change the reference the object points to. However, because structs are value types and they are immutable, the below code will not even compile showing the error: Cannot assign to property: ‘self’ is immutable

struct Driver {
var drivingLicenseNumber: String?
func assignLisence(with number: String) {
drivingLicenseNumber = number
}
}

If you are using Xcode as your development tool it will also suggest you to mark method mutating to make self mutable.

Xcode suggestion to mark method mutating

Once we mark the method mutating the error will disappear and the code will function as intended. We have already stated that structs are value types and immutable. What effect does the mutating function have on a struct? Well, it basically creates a new copy of the struct with modified value of the the property. The effect of the mutating keyword is as simple as this.

Mutating functions come a lot handier when used in composition of protocols. Because protocols can be implemented by both classes and structs and structs are value types, it might be worthy to consider adding mutating keyword to functions which need to change the value of self. While classes will “ignore” this keyword, it will be make the methods of the struct able to change the value of self.

If a method is defined as immutable in the protocol, but later adds mutating keyword, it is regarded as two different functions and as a result struct fails to conform to the protocol. Thus, it is in our best interest to consider adding the keyword in the definition of the function within protocol.

One last thing… Similar to mutating keyword, there is also nonmutating keyword in Swift. By default functions in Swift are nonmutating. The nonmutating keyword is not useful in this context, but they can be useful when creating setters for properties. I will try to cover usages nonmutating keyword in upcoming articles. Keep connected :)

--

--

Javid Museyibli
The Startup

Young enthusiastic software developer, currently full-time at PASHA Bank building Android and iOS applications.