Swift - Function inout parameter


Normally, function parameters and return values are passed by value.

You are given a copy of the parameters and their return values.

Parameter with the inout keyword can be passed by reference.

You can use this to swap two variables using a function, like so:


func swapValues(firstValue: inout Int, secondValue: inout Int) { 
    (firstValue, secondValue) = (secondValue, firstValue) 
var swap1 = 2 //from w  w w  . j  a  va 2  s  .  co  m
var swap2 = 3 
swapValues(firstValue: &swap1, secondValue: &swap2) 
print(swap1) // 3 
print(swap2) // 2


When you pass in a variable as an inout parameter, you must preface it with an ampersand (&).

This reminds you that its value is going to change when you call the function.

Related Topic