In-Out Parameters In Swift Functions
It’s not hard to mutate original provided arguments in functions, it’s just risky sometimes!
--
When coding in Swift, we usually don’t need to mutate the arguments that we provide to functions, and then make these changes visible back to the call site. We mostly use them as inputs to calculations or other expressions, and if necessary, we return some value from functions. But even if we tried to modify the parameter values, that would trigger a compile-time error, as parameter values are treated as constants, and therefore, they can’t be mutated.
To make my point about what I’m actually talking about, think of the following function that doubles the given number:
This simplistic example will work just fine, as it takes the parameter value as an input, it doubles it, it assigns the new value to another constant declared in the function, and then returns that value back to the caller. The next code though is not going to work:
Xcode will complain with the following error:
- Left side of mutating operator isn’t mutable: ‘number’ is a ‘let’ constant -
That says what I mentioned at the beginning; parameter values are considered to be constants, and they cannot be modified like variables can.
But, what if we really want to mutate the original parameter value? It might be sometimes much more suitable to do that, instead of returning a value from the function. Thankfully, we can, using in-out parameter values!
Mutating a parameter value
There is a certain way to let a function know that a parameter value should be treated as a variable and not as a constant. That is to…