gpt4 book ai didi

swift - Swift 函数是按值还是按引用分配/传递的?

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:42 25 4
gpt4 key购买 nike

当 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 函数被赋值/返回引用,因为 barfuncVar 相同范围内的另一个函数中,但它仍然有效(来自 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.

关于swift - Swift 函数是按值还是按引用分配/传递的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32358293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com