iOS Interview Guide: Escaping and Non-Escaping Closures in Swift

Nitin Aggarwal
Swiftable
Published in
6 min readAug 7, 2023

--

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.

--

--

Nitin Aggarwal
Swiftable

Lead Software Engineer (iOS), Technical Writer, Technical Interviewer, Helping you to crack your iOS interview.