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

Returning a function vs returning a closure

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

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

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

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

g 这样的内联函数确实保留了上下文。实际上函数是命名的闭包,或者闭包是未命名的函数(你喜欢哪个定义)。

如文档中所述:

Global and nested functions, as introduced in Functions, are actually special cases of closures

你写的不完全正确,因为根据 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() 确实捕获值。