DevPrep

All topics › The Swift Language

How do you pass a variable by reference?

Junior PRO

The idea

Swift passes arguments by value: the function receives a copy (for a class — a copy of the reference, so the object is shared without any extra keywords). To let a function modify the caller's variable, declare the parameter inout and pass it with &.

func increment(_ x: inout Int) { x += 1 }
var n = 1
increment(&n)
print(n)   // 2

func swapValues<T>(_ a: inout T, _ b: inout T) { (a, b) = (b, a) }
var x = 1, y = 2
swapValues(&x, &y)
print(x, y)   // 2 1

var arr = [1, 2]
// swapValues(&arr[0], &arr[1])
// error: overlapping accesses to 'arr', but modification requires
// exclusive access (law of exclusivity, SE-0176)
arr.swapAt(0, 1)

final class Box { var value = 0 }
func fill(_ box: Box) { box.value = 42 }   // shared reference, no inout needed
let box = Box()
fill(box)
print(box.value)   // 42

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store