Swift: Pass array by reference?

ma11hew28 picture ma11hew28 · Jun 16, 2014 · Viewed 81.4k times · Source

I want to pass my Swift Array account.chats to chatsViewController.chats by reference (so that when I add a chat to account.chats, chatsViewController.chats still points to account.chats). I.e., I don't want Swift to separate the two arrays when the length of account.chats changes.

Answer

Gene Karasev picture Gene Karasev · Oct 22, 2014

For function parameter operator we use:

let (it's default operator, so we can omit let) to make a parameter constant (it means we cannot modify even local copy);

var to make it variable (we can modify it locally, but it wont affect the external variable that has been passed to the function); and

inout to make it an in-out parameter. In-out means in fact passing variable by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with & - foo(&myVar) instead of just foo(myVar)

So do it like this:

var arr = [1, 2, 3]

func addItem(inout localArr: [Int]) {
    localArr.append(4)
}

addItem(&arr)    
println(arr) // it will print [1, 2, 3, 4]

To be exact it's not just a reference, but a real alias for the external variable, so you can do such a trick with any variable type, for example with integer (you can assign new value to it), though it may not be a good practice and it may be confusing to modify the primitive data types like this.