When To Use Mutating Functions in Swift Structs

One of the best things about Swift is that it has built-in features that allows for a lot of immutability in the architecture, making our code a lot cleaner and safer (highly recommend this talk on the subject if you haven’t seen it already!).

But what should you do when you actually need some mutability?

The Functional Approach

As an example, I have a tic-tac-toe board, and I need to change the state of a position on the board…

According to a clean functional programming approach, you would simply return a new board!

I prefer to use the functional approach because it doesn’t have any side-effects, I can keep my variables as constants, and of course, it is super clean to test!

However, this approach is not the best in all cases…

Using the Mutating Keyword

Let’s say I’m keeping track of how many tic-tac-toe games each user has won, so I create a Counter:

I can choose to use the functional approach here as well:

However, if you actually try to use the incrementing function, it will read like this:

This is super unintuitive and unreadable! So this is where I prefer to use the mutating keyword instead:

I don’t like the side-effects of the increment function, but it’s more than worth is for the readability:

Further, I can minimize the damage by making sure that the count variable cannot be reset externally (since it now has to be a var) by using a private setter:

Conclusion

When choosing whether to use the mutating keyword or the functional approach, I prefer to use the functional approach, but NOT at the expense of readability.

Writing tests is a good way to test out your interface to see if you the functional approach makes sense. If it feels way out of wack and unintuitive, go ahead and change it! Just make sure to use a private setter for the var!

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