Escaping Closures in Swift
In this article i hope to explain why we may use the @escaping attribute and explain the difference between the default @noescape.
If you used Swift 2 you may have used the @noescape attribute and you may know that this was later deprecated in Swift 3 with the introduction of the @escaping attribute. In order to understand why, let’s look at what we mean by @escaping.
Escaping Closures
A closure is said to be escaping when a closure passed in as an argument and executed after the scope of a function or when a function is returned. You can think of it as the closure “escaping” the body of a function.
Let’s look at an example.
As you can see the compiler is error-ing here because the completion block we pass as a parameter is escaping from the function body as it is getting called in the URLSessionDataTask block. In Swift 2 the above code would compile because the default was set to @escaping but for Swift 3 and higher the default is @nonescape. In fact, the @nonescape attribute is deprecated you can no longer use this attribute.
To fix the above issue we simply need to mark the completion block as @escaping like below.
Conclusion
To conclude there are several benefits to marking closures as @nonescape by default. The most obvious benefits are performance and the ability for the compiler to optimise your code. This also means that you can get away with with using weak references to self
in a @nonescape closure because it is invoked before the function returns.
I hope this article was useful and if i missed anything please let me know 🙂