Swift Inout Parameters
In programming, there are scenarios where we need to change the parameters we passed into a function. However, Swift doesn't allow us to change function parameters as function parameters are constant by default. If we try to change function parameters within the body of the function, we will get a compile-time error. It is a kind of security implemented so that we can't change the parameters by mistake.
However, if we want a function parameter to be changed inside a function body and we want the changes to persist outside the function scope. We can define the parameters as in-out parameters.
To define a parameter as in-out, swift provides an inout keyword before the parameter's type. The in-out parameter has the value changed inside the function and returned to replace the original value.
The in-out parameters are used as follows.
This is called call by value or copy-in-copy-out. When the computed property is passed as an in-out parameter, its getter method is called at the time of function call, and its setter method is called at the time of function return.
However, we can't define a constant or literal value as an in-out parameter since constant and literal values can't be modified. When we pass a variable as an inout parameter, we use an ampersand (&) before variable names to indicate that the variables are being passed as inout parameters in the function.
We also must notice that the inout parameters can't have default values, and variadic parameters can't be defined as inout.
Let's consider the following example, which defines a function swap() used to swap two integers by using a third variable.
It prints the following output on the console.
"a = 10 b = 20" "a = 20 b = 10"
The above example shows that the original values of two integer variables, a and b, are modified by the swap(_:_:) function, even though they were originally defined outside of the function.