In Swift, structs and value types are passed by value by default, just like in C#. But C# also has a very usable ref keyword, that forces the parameter to be passed by reference, so that the same instance could be changed inside the function and accessed from the caller's scope afterwards. Is there a way to achieve the same result in Swift?
Asked
Active
Viewed 2.9k times
1 Answers
103
Use the inout
qualifier for a function parameter.
func swapTwoInts(a: inout Int, b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
swapTwoInts(&someInt, &anotherInt)
See Function Parameters and Return Values in the docs.

rickster
- 124,678
- 26
- 272
- 326
-
Nice. 'var' is deprecated in Swift 3, but 'inout' works. – Canucklesandwich Jun 28 '16 at 19:21
-
Updated syntax - I'm using Xcode 8.0 and the current Swift 3 only accepts the `inout` qualifier just before the type, e.g.: `func swapTwoInts(a: inout Int, b: inout Int)` – Ryan H. Oct 20 '16 at 22:13
-
4@tracicot It's not the same. `var` was for having a mutable object in the local method scope - `inout` is for mutating the object at its own scope, from the method. Be careful. – Eric Aya Oct 21 '16 at 08:28
-
What if the method is written in Objective C? – Saad Mar 17 '17 at 11:33