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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With