When I think of Constants, I think of objects that cannot be changed at all. In Swift, that is true for basic types like Strings, Ints, Bools, etc. Once you assign them to a constant (using let), you can never re-assign them:
or change them:
Since I’ve used constants mostly for basic types before, I thought that objects also were completely immutable once they were assigned. Let’s take a simple Minion object:
Just like with the String example above, if I assign a minion object to a constant, I cannot re-assign it:
However, I was surprised to learn that you can still manipulate the variables of your object! So this works:
Basically, the constant here is a pointer for the specified object, which you can’t change. But you can still change the variable properties of the object being pointed to.
This is very powerful, since you can always guarantee that your class is manipulating the same object and nobody can re-assign it to something new, but at the same time, you can manipulate that one object as necessary.
@ColinEberhardt brought to my attention that if I do want the completely immutable behavior for an object, you can make it a struct!
@NatashaTheRobot change Minion to struct and it is completely immutable when defined as a constant. Which is very cool!
— Colin Eberhardt (@ColinEberhardt) August 22, 2014
I tried it out, and sure enough, I cannot change the variables in my struct:
This is because when you assign a struct to a constant, it copies the value of the struct. In contrast, when you assign a class object to a constant, it points to the reference of that class object in memory and you can therefore change the variables in the referenced object.