Escaping and Non-escaping Closures

Payal Kandlur
2 min readSep 18, 2021

Escaping closures

The escaping closures are the ones that when passed to the argument of a function, gets called after the function returns. Basically, the closure is allowed to escape😎 the function.

This means your closure has a scope outside that particular function! And how do you make your closure escaping? Just by adding the @escaping before the parameter’s type.

Here is an example:

var completionHandler: ((Int)->Void)?   

func getTotal(array:[Int], handler: @escaping ((Int)->Void)) {
var sum: Int = 0
for value in array {
sum += value
}
self.completionHandler = handler
}

func doSomething() {

self.getTotal(array: [16,756,442,6,23]) { [weak self](sum) in
print(sum)

}
}

Non-escaping closures

By default all closures now in Swift are non-escaping.

The non-escaping closure passed as the function argument, the closure gets executed with the function’s body and returns the compiler back. The passed closure goes out of scope and has no more existence in memory after the function execution ends. That is the closure is not allowed to escape!

func getTotal(array:[Int], handler: ((Int)->Void)) {

var sum: Int = 0
for value in array {
sum += value
}

handler(sum)
}

func doSomething() {
self.getTotal(array: [16,756,442,6,23]) { [weak self](sum) in
print(sum)
}
}

Having closure as non-escaping by default has a lot of advantages.

The most important benefits are performance and code optimisation by the compiler because if the compiler knows that the closure is non-escaping, will take care of the memory allocation for the closure.

That's all!😊 Thanks for reading, do tap the clap icon if you like this!

--

--