In-Out parameters in Swift
By default function parameters are constants in Swift.
If you attempt to change a parameter within a function you will get a compiler error.
To Solve this issue and enable a function to have an effect outside its scope we should use In-Out parameters.
How InOut Parameters work
1- When the function is called, the value of the argument is copied
2- Within the function’s body, that copy is modified
3- When the function returns, the copy’s value is assigned to the original argument
Code Example
First declare two Int variables
var firstInt = 3
var secondInt = 6
Then implement this function
func incrementIntegers(_ a : inout Int, _ b : inout Int) {
a = a + 1
b = b + 1
}
This simple function takes two Int parameters and increment each of them by 1
If you try removing the “inout” keyword the compiler will trigger an error because function parameters are constants by default and cannot be changed from within the function.
Now lets call this function but note that you have to prefix the parameter names with ampersand “&”
incrementIntegers(&firstInt, &secondInt)
print("firstInt:\(firstInt) and secondInt: \(secondInt)")
Result: firstInt =4 and secondInt = 7
You have successfully modified the values of firstInt and secondInt from within the function.
Important Notes about using InOut Parameters
- They cannot have default values
- Variadic parameters cannot be marked as inout
- You can only pass a variable as an inout parameter
- Constants or literal values cannot be passed as inout parameters
- You must place (&) directly before the variable’s name to indicate that it can be modified by the function
Read also Working with Date in Swift