Enviroment : Xcode 13.2.1
When trying to assign a closure to a local variable without an @escaping annotation, an error does not occur If the type is not specified, but an error occurs when the type is explicitly specified.
The code is as follows.
func foo(closure: ()->Void) {
let a = closure // <- non error
let b: () -> () = closure // <- error occurred
a()
}
The error message is "Using non-escaping parameter 'closure' in a context expecting an @escaping closure"
In order for an error to occur, it seems that it must occur in both cases, but it only occurs in one case, so I'm not sure what the problem is.
Is it a bug? or Does allocation work differently for implicit and explicit types?
Please reply. Thank you.
In the case of a, the compiler infers that a is a non-escaping closure. In the case of b, you’ve implicitly told the compiler that it’s escaping [1], and thus it complains.
Consider this addition to your code:
DispatchQueue.main.async(execute: a)
This fails with Converting non-escaping value to '@convention(block) () -> Void' may allow it to escape because a was inferred to be non-escaping.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Closure local variables and properties are always escaping. You can add @escaping if you want, but its redundant.