Swift’s mutating and nonmutating keywords
These are access modifiers for the individual methods of a struct or non-class protocols.
These apply also to the getter and setter methods of properties.
To understand these keywords, lets construct a struct MyStruct holding property underlyingValue of type Int:
class MyStruct {
private var underlyingValue: Int = 0
}
The ‘mutating’ keyword:
Lets try to change this value using a method called changeValue():
!!ERROR: CANNOT CHANGE THE INSTANCE VARIABLE
func changeValue() {
underlyingValue = 1
}
methods are nonmutating BY DEFAULT.
To solve this we will have to tell the compiler that this method should be able to change the value.
We do this by using the mutating keyword:
// WORKS
mutating func changeValue() {
underlyingValue = 1
}
The ‘nonmutating’ keyword:
The nonmutating keyword is used to mark a method method as something that should NOT modify the struct’s properties.
For example, setters of properties are mutating BY DEFAULT. (This is the opposite default behavior of methods)
Lets have another property called mutableValue that just gets and sets underlyingValue:
var mutableValue: Int {
get {
return underlyingValue
}
// default rights is 'mutating'
// same as:
// mutating set {
set {
underlyingValue = 1
}
}
to demonstrate the nonmutating keyword, lets have another property called immutableValue with nonmutating assigned to the setter:
var immutableValue: Int {
get {
return underlyingValue
}
nonmutating set {
// now cannot write to the instance var
//underlyingValue = 1
// do some stuff that doesn't write to any instance
//variables
print("Trying to set the immutableValue, but in vain! 😛")
}
}
Since setter is nonmutating, the compiler complains.
The default behaviors are:
methods: nonmutating
property setter: mutating
property getter: nonmutating