Thursday, March 19, 2015

Overview

In some cases, you would like to pass a variable by reference. In Swift, we use the inout and the & keys. Here’s an example of a generic swap.

1
2
3
4
5
6
7
8
9
10
11
12
13
var lucky = 7
var unlucky = 13

func swapTwoVariables<T>(inout first: T, inout second: T) {
    let temp = first
    first = second
    second = temp
}

swapTwoVariables(&lucky, &unlucky)

println("lucky: \(lucky)   unlucky: \(unlucky)")
// "lucky: 13   unlucky: 7"

Random Posts