Understanding @escaping and @non-escaping closures

Pradeep Dahiya (Apple Developer)
2 min readMay 10, 2021
Photo by Holly Mandarich on Unsplash

During the code, you may deal with functions with parameters escaping or non-escaping. Have you ever given thought 🤔 what is it ? Let’s discuss this and clear our understanding with real meanings.

Closures ?

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

didn’t get this !!! no problem

So everything runs around word “Escaping” lets see what google says about this word

A escaping closure tells the compiler that the closure you pass to any function as a parameter can be executed outside the body of that function.it means we can pass escaping closure to another variable.

Okay let’s do some code to correlate the meaning of escape to programming

Here we are passing closure parameters to another variable in simple words function have a closure which can be escaped.

look up the counterpart with non-escaping closure parameter

This is an example of non-escaping closure. A non-escaping closure tells the compiler 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.

One main difference between escaping and non-escaping closure is that in @escaping we are holding memory location and for non-escaping we are not holding memory location.

History

In Swift 1.x and Swift 2.x, the closure parameter was @escaping by default, meaning that closure can be escaped during the function body execution. If you don’t want to escape closure parameters, mark it as @non-escaping.In Swift 3.x, Apple made a change: closure parameters became @non-escaping by default.

Hope this blog will clear your understanding for @escaping and @non-escaping closures.Check out the next part for more detailed discussion on the advanced topic of this series.

--

--