Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a function vs returning a closure

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 }
}
like image 610
Danyal Aytekin Avatar asked Jun 15 '26 21:06

Danyal Aytekin


2 Answers

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.

like image 115
Dániel Nagy Avatar answered Jun 17 '26 11:06

Dániel Nagy


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

like image 43
Antonio Avatar answered Jun 17 '26 11:06

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!