func test(f: () -> ()) {
let a = f
let b: () -> () = f // error
a()
b()
}
The only difference between a and b is whether the type is specified or not.
But what is the reason for the error to be printed only in b?
Please explain the clear difference between a and b.
CodePudding user response:
The error is shown because 'b' and 'f' do have different signatures.
'b' is an escaping closure 'f' is not.
when doing:
let a = f
you are copying 'f'. The signature stays the same "nonescaping () -> ()".
Declaring a closure in function definition gives you implicit 'nonescaping' in body gives you implicit 'escaping'.
Decorating your closure in the header with @escaping will solve the problem.
func test(f: @escaping () -> ()) {
If you want to know more: https://medium.com/swiftcommmunity/what-do-mean-escaping-and-nonescaping-closures-in-swift-d404d721f39d

