Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift have something like "ref" keyword that forces parameter to be passed by reference?

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?

like image 452
Max Yankov Avatar asked Oct 11 '22 00:10

Max Yankov


People also ask

Is Swift pass by value or pass by reference?

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.

Which keyword is used to pass the parameters by reference?

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.

How do you pass a parameter in Swift?

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.

Are parameters passed by reference?

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.


1 Answers

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.

like image 102
rickster Avatar answered Oct 16 '22 10:10

rickster