Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Swift functions assigned/passed by value or by reference?

When a function in Swift is assigned to a variable or returned, as a nested function, from a higher-level function, is it passed by value or by reference? When I write:

func foo() -> Bool
{
    return false
}

var funcVar = foo

does funcVar receive a reference to foo(), or is a copy of foo() created and stored in memory with the "funcVar" name? Same question for the following code:

func otherfoo() -> (Int) -> ()
{
    func bar(num :Int) {}
    return bar
}

var funcVar = otherfoo()

The second example in particular puzzles me because, if I call funcVar(3) I should not be able to access bar in the case functions are assigned/returned by reference, since bar is inside another function at the same scope of funcVar, but it still works (coming from a C++ background I'm just surprised it compiles). Could somebody please shed some light on the matter for me?

like image 755
MustangXY Avatar asked Sep 02 '15 16:09

MustangXY


People also ask

Is Swift pass by reference or value?

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.

Is Swift pass by value or pass by reference by default?

it is Pass By Value. Pass By Reference Classes Always Use Pass by reference in which only address of occupied memory is copied, when we change similarly as in struct change the value of B , Both A & B is changed because of reference is copied,.

How do you pass a function in Swift?

To pass a function as a parameter into another function in Swift, the accepted parameter type needs to describe a function. Now you can call this function by passing it an argument that is any function that takes two doubles and returns a double. This is the quick answer.

Are Swift closures value or reference types?

The Basics. In Swift, structs, enums and tuples are all value types, while classes and closures are reference types.


1 Answers

From the Apple documentation:

In the example above, incrementBySeven and incrementByTen are constants, but the closures these constants refer to are still able to increment the runningTotal variables that they have captured. This is because functions and closures are reference types.

Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.

like image 68
Aaron Rasmussen Avatar answered Sep 21 '22 20:09

Aaron Rasmussen