A closure returning a closure bug

Looks like a bug in closure returning a closure: compiler insists on making "foo" taking escaping closure parameter, while it compiles fine if I formulate the code a bit differently:

func foo(_ execute: (Int) -> Void) { // @escaping is unwanted here
}

func bar() {
    // a closure (returning a closure (returning a closure))

    foo({(i:Int) in {(j:Int) in {(k:Int) in}}}(1)(2)) // this compiles OK
    
    foo({(i:Int) in {(k:Int) in}}(1)) // Error: Converting non-escaping value to '(Int) -> Void' may allow it to escape
    
    // Equivalent code:
    
    let kclosure = {(k:Int) in}
    let jclosure = {(j:Int) in kclosure}
    let iclosure = {(i:Int) in jclosure}
    foo(iclosure(1)(2)) // this compiles OK

    let new_iclosure = {(i:Int) in kclosure}
    foo(new_iclosure(1)) // this still compiles OK
    foo({(i:Int) in kclosure}(1)) // so does this
}
2 Likes