In Swift, as I understand it, closures preserve their environment, while normal functions do not.
Consider f
(returning a function) and h
(returning a closure) below. Both f()()
and h()()
return 3
. Why doesn't f()()
cause a runtime error?
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.
So g() do capture values.
An inline function like g
does preserve the context. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.