Mutable Function Parameters

Today I decided to take a look at the upcoming Swift 3.0 changes. If you are interested in reading about implemented proposals, please see Swift Evolution page on Github. This article is in addition to the article I wrote about Swift 2.2 changes that can be found here.

SE-0003: Removing var from Function Parameters – is the one I want to talk about. Function parameters, by default, are constants. However, it was possible to declare the parameter as a variable.

To give you a better idea of what I am referring to, let’s assume we need to write a function that takes in a string, reverses it, and then returns the new result:

The function parameter was declared as a variable that allowed me to perform actions on it without creating a mutable copy (nice). Farther more, the original string (see line 26) was never mutated (nice again). Having Swift support this ability was great since it eliminated the need for mutable copy. So why was this ability removed in Swift 3.0? The motivation is:

Using var annotations on function parameters have limited utility, optimizing for a line of code at the cost of confusion with inout, which has the semantics most people expect.

My challenge with inout is as that it is designed to mutate original input.

Here we are mutating the original. It’s OK to do, but what if we needed to keep the original around? In that case we need to either make a copy of the original before reversing it, or rewrite function implementation and make a mutable copy of the parameter and perform actions on it.

The ability to declare function parameters as vars eliminated the need to make local, mutable copies. inout on the other hand is designed to mutate the original input. I am not sure where the confusion was coming from… but it’s just me.

There are a couple of other changes already merged into Swift’s main branch, you can find the rest here.

Mutable Function Parameters

Leave a Reply

Your email address will not be published. Required fields are marked *