I'm new to Swift and I'm trying to learn the concept of 'inout' keyword. I saw this code in "the swift programming language 2.1". My question is, why is there a "&" in "swap(&someInt, &anotherInt)". What does it represent? What is its function?
func swapTwoInts(inout a: Int, inout _ b: Int){
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swap(&someInt, &anotherInt)
print("someInt is now \(someInt) and anotherInt is now \(anotherInt)")
Just like passing by reference in C++, the ampersands in the calling bit of the code just tell the compiler that you give permission to function swapTwoInts
to change both someInt
and anotherInt
. If you had not put the ampersands there, the code would not compile.