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?
In Swift, instances of classes are passed by reference. This is similar to how classes are implemented in Ruby and Objective-C. It implies that an instance of a class can have several owners that share a copy. Instances of structures and enumerations are passed by value.
Passing an argument by reference. When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable.
To pass function as parameter to another function in Swift, declare the parameter to receive a function with specific parameters and return type. The syntax to declare the parameter that can accept a function is same as that of declaring a variable to store a function.
An out-parameter represents information that is passed from the function back to its caller. The function accomplishes that by storing a value into that parameter. Use call by reference or call by pointer for an out-parameter. For example, the following function has two in-parameters and two out-parameters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With