Swift - Function inout parameter

Introduction

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:

Demo

func swapValues(firstValue: inout Int, secondValue: inout Int) { 
    (firstValue, secondValue) = (secondValue, firstValue) 
} 
var swap1 = 2 //  ww w . ja  v  a  2s  . c  o  m
var swap2 = 3 
swapValues(firstValue: &swap1, secondValue: &swap2) 
print(swap1) // 3 
print(swap2) // 2

Result

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