How do escaping and nonescaping closure parameters differ in Swift?

Instruction: Show the default closure-parameter syntax and @escaping syntax. Explain lifetime permission separately from reference ownership, and demonstrate how to prevent a stored closure from retaining its owner indefinitely.

Context: This question assesses the candidate's understanding of closure capture semantics in Swift, focusing on the distinction between closures that can escape the function they were passed into and those that cannot.

Updated

Example answer

A closure parameter is nonescaping by default: it cannot be stored for use after that call returns. There is no @nonescaping annotation in this syntax. Write @escaping when the closure may outlive the call, for example when storing a completion handler. Escaping permits a lifetime; it neither requires asynchronous execution nor prevents reference cycles.

func applyNow(_ operation: () -> Int) -> Int {
    operation()
}
assert(applyNow { 2 + 3 } == 5)

final class Job {
    var completion: (() -> Void)?
    var completed = false

    func store(_ callback: @escaping () -> Void) {
        completion = callback
    }

    func start() {
        store { [weak self] in
            self?.completed = true
        }
    }

    func finish() {
        let callback = completion
        completion = nil
        callback?()
    }
}

var job: Job? = Job()
weak var observedJob = job
job?.start()
job?.finish()
assert(job?.completed == true)
job = nil
assert(observedJob == nil)

Without [weak self], a stored closure using self.completed would create Job → closure → Job. @escaping allows storing that closure; it does not break the cycle. Weak capture avoids retaining the job and explicitly accepts that it may disappear before completion. unowned is only appropriate when the referenced object's lifetime is guaranteed; using it after deallocation traps. Clearing a completed or cancelled callback can also release ownership, but a callback that never completes must not retain its owner indefinitely.

Sources

Swift closures and escaping parameters; Closure reference cycles.

Related Questions