Member-only story
iOS Interview Guide: Escaping and Non-Escaping Closures in Swift

Level: Intermediate, Priority: High
In your interviews, escaping and non-escaping closures demonstrate strong functions and closure skills and problem-solving abilities, enabling you to write efficient and concise code. Be ready to prepare these questions for your iOS interviews as these are the most common questions for interviews.
Escape: to manage to get away from a place where you do not want to be;
Q1. What is the difference between escaping and non-escaping closures?
Swift closures can capture and store references to constants and variables from the context within which they are defined. These captured values can lead to a reference cycle. This is where the closure captures a reference to a value that also has a strong reference back to the closure, causing a memory leak.
To avoid memory leaks, Swift provides two types of closure: escaping and non-escaping closures.
Non-Escaping Closures
- A non-escaping closure guarantees to be executed before the function it is passed to returns.
- The compiler knows that the closure won’t be used outside the function and optimize the code accordingly.
- Non-escaping closures are the default type of closure in Swift.
// Non-Escaping Closure
func execute(closure: () -> Void) {
print("Executing non-escaping closure")
closure()
print("Finished executing non-escaping closure")
}
execute {
print("This is a non-escaping closure")
}
// Output:
// Executing non-escaping closure
// This is a non-escaping closure
// Finished executing non-escaping closure
Escaping Closures
- An escaping closure is passed as an argument to a function but called after the function returns.
- The closure is stored in memory until it is called, which means it can outlive the function that created it. In other words, the closure “escapes” from the function.
// Escaping Closure
var escapingClosureArray: [() -> Void] = []
func addEscapingClosureToQueue(closure: @escaping () -> Void) {…