简体   繁体   English

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

[英]Returning a function vs returning a closure

In Swift, as I understand it, closures preserve their environment, while normal functions do not. 在Swift中,据我所知,闭包保留了他们的环境,而普通的功能却没有。

Consider f (returning a function) and h (returning a closure) below. 考虑下面的f (返回一个函数)和h (返回一个闭包)。 Both f()() and h()() return 3 . f()()h()()返回3 Why doesn't f()() cause a runtime error? 为什么f()()不会导致运行时错误?

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

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

What you wrote is not exactly true, because according to the 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. Closure表达式是一种未命名的闭包,用轻量级语法编写,可以从周围的上下文中捕获值。

So g() do capture values. 所以g()会捕获值。

An inline function like g does preserve the context. g这样的内联函数确实保留了上下文。 Actually functions are named closures, or closures are unnamed functions (whichever definition you prefer). 实际上,函数被命名为闭包,或者闭包是未命名的函数(无论您喜欢哪种定义)。

As stated in the documentation: 如文档中所述:

Global and nested functions, as introduced in Functions, are actually special cases of closures 函数中引入的全局函数和嵌套函数实际上是闭包的特例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM