Swift 函数 assigned/passed 是按值还是按引用?

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

当Swift中的函数被赋值给变量或作为嵌套函数从更高层函数返回时,它是按值传递还是按引用传递?当我写:

func foo() -> Bool
{
    return false
}

var funcVar = foo

funcVar 是否接收到对 foo() 的引用,或者 foo() 的副本是否已创建并以 "funcVar" 名称存储在内存中?以下代码的相同问题:

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

var funcVar = otherfoo()

第二个例子特别让我困惑,因为如果我调用 funcVar(3) 我不应该能够访问 bar,因为函数是 assigned/returned 的引用,因为 bar 位于 funcVar 相同范围的另一个函数中,但它仍然有效(来自 C++ 背景,我只是惊讶它编译)。 有人可以为我解释一下这个问题吗?

来自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.

首先,everything in Swift是按值赋值,everything in Swift是如果参数没有 ref 并且您不使用 & 传递它,则按值传递。 (如果参数有ref,你用&传递,就是引用传递。)无论类型如何,都是如此。

不清楚你在问什么。您可能会问函数是值类型(如结构)还是引用类型(如对对象的引用),这是一个不同的问题。答案是,因为 Swift 中的函数是不可变的(不存在可以更改的可变 "contents" 函数),所以在语义上无法区分它是值类型还是引用类型。这两种方式都没有区别。

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

我不明白你在说什么。函数是第一个 class 公民。所以一旦你有了一个函数值,你就可以使用它,你可以传递它,你可以 return 它,就像其他任何东西一样,谁得到这个函数就可以像使用任何其他函数一样使用它。函数值是复制的值类型还是对引用计数对象的引用都没有区别。

函数是 swift 中的引用类型。通过代码示例进一步说明这一点。

func countAdder(_ word: String)-> () -> (){
var count = 0
func currentCount(){
    count += 1
    print(count)
}
return currentCount
}
let countedWord = countAdder("Hello")
let countedWordTwo = countAdder("World")
countedWord() // count is 1
countedWordTwo() // count is  1
//Lets try this

let countedWord = countAdder("Hello")
let countedWordTwo = countedWord
countedWord() // count is  1
countedWordTwo() // now count is 2

我希望这个概念解释清楚。