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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to draw images programmatically without Views or UIViews for your Tests

The Façade Design Pattern in Swift

Networking Swift

Camera preview and a QR-code Scanner in SwiftUI

How to Animate Auto Layout Constraints

Linked Lists and LL Algorithms in Swift

Error Handling in Swift

Screen Brightness Using Combine

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
Vijay Chandran Jayachandran

Vijay Chandran Jayachandran

Engineer

More from Medium

How to resolve the swiping right action when trying to navigate to a previous screen in iOS.

Swift 5.6: Combining Logical Operators

Understanding Git Branches

What is the Variables and Constants in Swift Language ?