gpt4 book ai didi

function - 返回一个函数 vs 返回一个闭包

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

在 Swift 中,据我了解,闭包会保留其环境,而普通函数则不会。

考虑下面的 f(返回一个函数)和 h(返回一个闭包)。 f()()h()() 都返回 3。为什么 f()() 不会导致运行时错误?

func f() -> () -> Int { 
let a = 3
func g() -> Int {
return a
}
return g
}

func h() -> () -> Int {
let a = 3
return { () in a }
}

最佳答案

你写的不完全正确,因为根据 documentation :

Global functions are closures that have a name and do not capture any values.

Nested functions are closures that have a name and can capture values from their enclosing function.

Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

所以 g() 确实捕获值。

关于function - 返回一个函数 vs 返回一个闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28296814/

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