← All topics/Swift language features

Practical interview questions

Scenario-style prompts with sample answer outlines. Focus is on how you would design and reason in real codebases.

Question 5

Closures — captures, @escaping, trailing syntax

What does @escaping mean for a closure parameter? When can a closure be implicitly non-escaping?

Answer outline

Non-escaping closures may only run before the callee returns. The closure cannot outlive the call.

Closures are implicitly Non-escaping by default. (they won't be marked as non-escaping.)

@escaping means the closure may outlive the function stored in a property, invoked asynchronously, or called later. Escaping closures capture self strongly by default, so retain cycles are a design concern.

Principles

  • @autoclosure defers evaluation—uncommon; easy to misuse. Assert is an example of an autoclosure.
Escaping vs non-escaping
func load(completion: @escaping (Result<Data, Error>) -> Void) {
    // Stored or async-invoked later → @escaping required
}

func syncMap(_ x: Int, _ f: (Int) -> Int) -> Int {
    f(x) // f cannot escape before return — non-escaping by default
}