Escaping vs Nonescaping closures in Swift

For those who have used closure, you may have encountered @escaping or @nonescaping. What the hell is that? To understand these two concepts, let’s refresh our memory and see what is a closure according to Apple’s documentation.

Closures are self-contained blocks of functionality that can be passed around and used in your code.

Nonescaping closure

Life cycle of non-escaping closure

  1. Pass a closure into a function
  2. The function executes that closure
  3. The function returns

Basically, a non-escape closure can only run the contents inside of it’s body, anything outside of it’s closure cannot be used. A non-escape closure tells the complier that the closure you pass in will be executed within the body of that function and nowhere else. When the function ends, the closure will no longer exist in memory. For example, if we needed to extract any values within our closure to be used outside of it, we may not do so. During the earlier days of Swift, closure parameters were escaping by default. Due to better memory management and optimizations, Swift has changed all closures to be non-escaping by default.

var closuresArray: [() -> Void] = []
func doClosures(completion: () -> Void){
passing non-escaping parameter 'completion' to function expecting an @escaping closure

Here is an example of an non-escaping closure. Here we have an empty array of closure and a function that includes a closure. If we were to append the closure in the function to the array of closure, we cannot do so because it is defaulted to non-escape. One great thing about Xcode is that it will that you that you need an escaping closure and can implement it for you.

Escaping Closure

Essentially escaping closure is the opposite of non-escaping closure. An escaping closure grants the ability of the closure to outlive the function and can be stored elsewhere. By using escape closure, the closure will have existence in memory until all of it’s content have been executed. To implement escaping closure, all we have to do is put @escaping in front of our closure. If you are unsure whether your closure needs escaping, no worries, as I’ve said before the complier is smart enough to let you know.

There are several ways when we need to implement an escaping closure. One instance is when we use asynchronous execution. When we are dealing with dispatch queue, the queue will hold onto the closure for you, and when the queue is done completing its work, then it will return back to the closure and complete it. Since dispatch queue is outside of the scope, we need to use escaping closure. Another instance is when we need to store our closure to a global variable, property, or any bit of storage that lives on past the function.

Thanks for tuning in! 😎