Swift’s nonmutating Keyword
01 May 2016In preparing my recent “Hidden Gems in Swift” talk, I carefully combed through Swift’s “Lexical Structure” section. One keyword that stuck out to me, but ultimately didn’t make it into the talk was nonmutating
. Much like the @nonobjc
attribute, it surprised me that I hadn’t seen this keyword in the wild.
In searching for example uses, I stumbled upon this conversation between Andy Matuschak and Sidney San Martín:
Interesting new Swift keyword I learned about today: "nonmutating."
— Andy Matuschak (@andy_matuschak) October 15, 2014
e.g. UnsafeMutablePointer's
var memory: T { get nonmutating set }
@andy_matuschak I just discovered this myself. I'm using an enum to manage app defaults, and now I can…
— Sidney (@Sidnicious) October 12, 2015
AppDefault.Bounciness.intValue = 5
@Sidnicious Yikes. What does that mean? Have a gist?
— Andy Matuschak (@andy_matuschak) October 12, 2015
@andy_matuschak Think it's too much? https://t.co/WiK4Onj8B1
— Sidney (@Sidnicious) October 12, 2015
@Sidnicious Yes. :)
— Andy Matuschak (@andy_matuschak) October 12, 2015
That setter *is* mutating. This will break compilation semantics.
@andy_matuschak Hah! That's fair. I'd consider it nonmutating, though, because it doesn't change the instance itself, just global state. No?
— Sidney (@Sidnicious) October 12, 2015
@Sidnicious Hm. I think you’re right, actually!
— Andy Matuschak (@andy_matuschak) October 12, 2015
Stepping through Sidney’s example, we can see how nonmutating
signals that a setter doesn’t modify the containing instance, but instead has global side effects.
Whether or not this is good practice is a larger question. But, it’s definitely worth adding to your tool belt!