inout parameters
If we want to change the value of a parameter and we want those changes to persist once the function ends, we need to define the parameter as an inout
parameter. Any changes made to an inout
parameter are passed back to the variable that was used in the function call.
Two things to keep in mind when we use inout
parameters are that these parameters cannot have default values and that they cannot be variadic parameters.
Let's look at how to use inout
parameters to swap the values of two variables:
func reverse(first: inout String, second: inout String) {
let tmp = first
first = second
second = tmp
}
This function will accept two parameters and swap the values of the variables that are used in the function call. When we make the function call, we put an ampersand (&
) in front of the variable name, indicating that the function can modify its value. The following example shows how to call the reverse
function:
var one = "...