[swift-users] Compiler refuses non-escaping closure calls in nested function
Zhao Xin
owenzx at gmail.com
Sun Oct 9 19:45:31 CDT 2016
I changed you code `let result = closure(n)` to `let result = closure(1)`.
I thought that should eliminate the error. It didn't. The compiler asked me
to change the whole code as below:
func mainFunction(closure: @escaping (Int) -> Int) -> Int {
func closureDoubled(_ n: Int) -> Int {
let result = closure(1)
return 2*result
}
let temp1 = closure(1)
let temp2 = closureDoubled(1)
return temp1+temp2
}
So I think in `func closureDoubled(_ n: Int) -> Int`, the `closure` is
escaping other than non-escaping. The result is not calculated inside the
function `closureDoubled`, it was calculated at `return temp1+temp2`, that
is what I think can explain the behavior.
I don't know why at first. It just like there were two ways to do the job,
you thought it worked in this way, but it chose the other way. Both ways
lead to the same result.
Then I changed your code to
func mainFunction2(closure: (Int) -> Int) -> Int {
func closureDoubled(_ n: Int, closure2:(Int) -> Int) -> Int {
let result = closure2(1)
return 2*result
}
let temp1 = closure(1)
let temp2 = closureDoubled(1, closure2: closure)
return temp1+temp2
}
Everything works as expected now. So I think the reason is just because of
`closure` was not define in `func closureDoubled` in the first
code snippet. It was defined outside, so it was escaping. What do you think?
Zhaoxin
On Mon, Oct 10, 2016 at 8:07 AM, Jean-Denis Muys via swift-users <
swift-users at swift.org> wrote:
> Here is a contrived reduction of my problem
>
> func mainFunction(closure:(Int) -> Int) -> Int {
>
>
> func closureDoubled(_ n: Int) -> Int {
>
> let result = closure(n)
>
> return 2*result
>
> }
>
>
> let temp1 = closure(1)
>
> let temp2 = closureDoubled(1)
>
> return temp1+temp2
>
> }
>
> The line "let result = closure(n)" is refused by the compiler with the
> error message "declaration over non closing parameter may allow it to
> escape".
>
> First off, while I know what an escaping or a non-escaping closure is, I
> find this error message utterly impossible to understand. To begin with,
> the sentence "non closing parameter" is meaningless to me.
>
> In any case, my main function is passed a non-escaping closure. I want to
> call it from inside it, the compiler is ok with. I want also to call it
> from a nested function, but the compiler disagrees.
>
> I believe the compiler should not complain here. Did I miss anything?
>
> Jean-Denis
>
>
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161010/ad76f9b8/attachment.html>
More information about the swift-users
mailing list