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 the 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 = "One" 
var two = "Two" 
reverse(first: &one, second: &two)  
print("one: (one) two: (two)") 

In the preceding example, we set variable one to a value of One and variable two to a value of Two. We then called the reverse()function with the one and two variables. Once the reverse()function has returned, the variable named one will contain the value Two, while the variable named two will contain the value One.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset