Optional Closures in swift

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:

Compiler raising an error requires explicit use of self

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:

https://www.swiftwithvincent.com/newsletter/are-optional-closures-escaping-or-not

https://www.jessesquires.com/blog/2018/06/10/why-optional-swift-closures-are-escaping/

要查看或添加评论,请登录

社区洞察

其他会员也浏览了