Swift: Manipulating Constant Objects

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:

Swift String Immutable

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:

Screen Shot 2014-08-22 at 7.56.18 AM

Just like with the String example above, if I assign a minion object to a constant, I cannot re-assign it:

Screen Shot 2014-08-22 at 8.01.00 AM

However, I was surprised to learn that you can still manipulate the variables of your object! So this works:

Screen Shot 2014-08-22 at 8.02.37 AM

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!

I tried it out, and sure enough, I cannot change the variables in my struct:

Screen Shot 2014-08-22 at 6.18.55 PM

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.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.