Swift’s mutating and nonmutating keywords

class MyStruct {
private var underlyingValue: Int = 0
}
!!ERROR: CANNOT CHANGE THE INSTANCE VARIABLE
mutating func changeValue() {
underlyingValue = 1
}
// WORKS
mutating func changeValue() {
underlyingValue = 1
}
var mutableValue: Int {
get {
return underlyingValue
}

// default rights is 'mutating'
// same as:
// mutating set {
set {
underlyingValue = 1
}
}
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! 😛")
}
}
methods: nonmutating
property setter: mutating
property getter: nonmutating

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store