Optional Closures in swift
Closures in Swift are by default non-escaping starting from swift3; to define it as escaping, you must explicitly mention this.
So today's question: Are optional closures escaping or non-escaping?
We know that escaping closures can lead to retain cycles so the compiler asks us to explicitly capture self on this type of closure, so if we write an optional closure and have a compiler issue regarding missing self inside the closure block hence it's an escaping one, simple Right???
let's do a small experiment:
So we have our answer: optional closures are indeed escaping in Swift!
Now the question that comes next is: why Swift doesn't ask to explicitly add the @esacping attribute?
@esacping attribute is added to function type so for non-optional closures like this ()-> Void it can be added, but for optional ones (()-> Void)? this is not a function.
if we go to the Optionl declaration it's an enum with two cases None and some(Wrapped) with an associated value. since this is not a function hence we can't add the @esacping attribute.
the next question is: why does Swift treat optional closure as escaping?
On Twitter, David Hart explained:
It doesn’t make sense to add escaping annotations to optional closures because they aren’t function types: they are basically an enum (Optional) containing a function, the same way you would store a closure in any type: it’s implicitly escaping because it’s owned by another type.
I hope you find it useful ??
Resources: