Search code examples
swiftfunctionpass-by-referencevariable-assignmentpass-by-value

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?


Solution

  • 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.