What does an ampersand (&) mean in the Swift language?

It works as an inout to make the variable an in-out parameter. In-out means in fact passing value 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)

As you see you can use that in error handing in Swift where you have to create an error reference and pass it to the function using & the function will populate the error value if an error occur or pass the variable back as it was before

Why do we use it? Sometimes a function already returns other values and just returning another one (like an error) would be confusing, so we pass it as an inout. Other times we want the values to be populated by the function so we don't have to iterate over lots of return values, since the function already did it for us - among other possible uses.

I hope that helps you!


It means that it is an in-out variable. You can do something directly with that variable. It is passed by address, not as a copy.

For example:

var temp = 10
func add(inout a: Int){
    a++
}
add(inout:&temp)
temp // 11