[Swift] How to Pass By Reference via The Use of ‘inout’

xcode  When defining a function the keyword ‘inout‘ is used in front of the variable name to denote an in-out parameter, which sets up the function as a kind of “pass-by-reference” function. Note, this is not real pass-by-reference as the variable is still copied within the function, manipulated and the passed back out. 

What is an in-out parameter?
An in-out parameter is a parameter that has the keyword ‘inout‘ at the start of its definition. This parameter is like an alias or reference to the variable in the calling function. Changes made to the inout variable inside the function are retained when the function call completes. For example, we define our function as such:

Look at this function that swaps the values of two variables: swapCEO

func swapCEO(inout person: String, inout withPerson: String) {...}

Where the keyword ‘inout‘ denotes the parameter ‘person‘ and parameter withPerson of type ‘String‘ will have a value passed in and then passed out. The value passed out may or may not be changed, but should it be changed this will be perfectly acceptable.

When the swapCEO function is called, each of its two arguments must have prefixed an ampersand (&), like so:

swapCEO(&appleCEO, &microsoftCEO)

By prefixing an ampersand (&) to our arguments we are indicating the variables passed in may be modified.

Note: It is an error to use the keyword ‘inout‘ in a function definition but not prefix an ampersand(&) to an argument when that function is called.

Let’s See This in Action

We declare two variables to serve as place holders for the names of well known CEO’s. Time Cook the current CEO of Apple is stored in the variable appleCEO and Satya Nadella the current CEO of Microsoft is stored in the variable microsoftCEO.

var appleCEO = "Tim Cook"
var microsoftCEO = "Satya Nadella"

As previously mentioned, to swap the values of our two variables we simple call swapCEO and prefix the ampersand (&) to each of variables.

swapCEO(&appleCEO, &microsoftCEO)

We can now print the variables and see if this worked.

See the full execution from a Playground Session Below

playground

playground

This same concept may be used on any type, not just String, when you need a function to modify its variable parameters.

This entry was posted in Devel. Bookmark the permalink.

Leave a comment