SwiftMidMCQ

What is `@escaping` in a closure?

Test your knowledge:

Explanation & Code

Answer: A closure marked @escaping can outlive the function it was passed into — it "escapes" the function's scope. Non-escaping closures are executed synchronously before the function returns.

Code Example:

// @escaping — stored and called later (e.g. async completion)
func fetchData(completion: @escaping (Result<Data, Error>) -> Void) {
    URLSession.shared.dataTask(with: url) { data, _, error in
        if let data = data {
            completion(.success(data))
        }
    }.resume()
}

// Non-escaping (default) — called inline, can be optimized by the compiler
func performOperation(action: () -> Void) {
    action() // called immediately, before function returns
}

Key Points:

  • Use @escaping for async callbacks, stored closures, delegate-style patterns
  • Non-escaping closures don't need self. to capture properties

Rate your understanding:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.