skip to content

In Swift, why must an image downloader's completion-handler parameter be marked @escaping, and why are closure parameters non-escaping by default?

level: middleimportance: must knowfreq 72%

answer

  1. outlives the call
  2. stored, then called after return
  3. the default since Swift 3
  4. optional closures already escape
  5. explicit self inside escaping bodies

basics

~20 s

A closure escapes when it is stored or called after the function returns, as a completion handler is, so Swift requires @escaping on that parameter. Non-escaping is the default because the compiler can then guarantee the closure's lifetime ends with the call.

solid answer

~50 s

`download(_:completion:)` returns as soon as it starts the request and calls `completion` later, so the closure has to outlive the call: it is kept in a property or a collection, which requires `completion: @escaping (String) -> Void`. Without the attribute the compiler rejects the store with `assigning non-escaping parameter 'completion' to an '@escaping' closure`. Function-typed parameters have been non-escaping by default since Swift 3 (SE-0103): a non-escaping closure is known to finish before the call returns, so it may use `self` implicitly and capture `inout` parameters, and the compiler has room to avoid costs an escaping closure needs, such as a heap box for each captured `var`. Two details: an optional closure parameter like `((String) -> Void)?` is already escaping, and an escaping closure must write `self.` or capture `self` explicitly, because keeping `self` there can extend an object's lifetime.

code

swift · 22 lines
swift
final class ImageDownloader {
    private var pending: [String: (String) -> Void] = [:]

    // Stored and called after download(_:completion:) returns, so it must be @escaping.
    func download(_ url: String, completion: @escaping (String) -> Void) {
        pending[url] = completion
    }

    // Non-escaping: called before forEachPendingURL(_:) returns and never stored.
    func forEachPendingURL(_ body: (String) -> Void) {
        for url in pending.keys.sorted() { body(url) }
    }

    func finish(_ url: String) {
        pending.removeValue(forKey: url)?("bytes of \(url)")
    }
}

let downloader = ImageDownloader()
downloader.download("cat.png") { image in print("received", image) }
downloader.forEachPendingURL { url in print("waiting for", url) }
downloader.finish("cat.png")

go deeper

for a junior

Remember the trigger: if the function stores the closure or calls it after returning, as a completion handler does, the parameter needs @escaping.

for a middle

Explain why non-escaping is the default since Swift 3, which compiler errors appear when a closure escapes by accident, and why optional closure parameters already escape.

for a senior

Read @escaping in a signature as a lifetime promise: what it lets the closure keep alive, why structs cannot hand out a mutable self, and when withoutActuallyEscaping is safe.

for a principal

Keep escaping closures out of APIs that do not need them, so callers get implicit self and simpler capture reasoning, and reserve @escaping for genuinely asynchronous or stored callbacks.

## What "escaping" means A closure passed into a function **escapes** when it can be called after that function has returned. Two things make that happen: - the function **stores** the closure — in a property, a dictionary of pending requests, a global, an array of observers; - the function hands it to something that calls it **later**, such as an asynchronous API that itself takes an escaping closure. An image downloader is the textbook case. `download(_:completion:)` starts the network work and returns at once; `completion` runs when the bytes arrive, long after the call frame is gone. So the parameter must be declared `completion: @escaping (String) -> Void`. If you forget, the compiler says exactly what is wrong. Storing a non-escaping parameter in a property produces `assigning non-escaping parameter 'completion' to an '@escaping' closure`; appending it to an array produces `converting non-escaping parameter 'completion' to generic parameter 'Element' may allow it to escape`. ## Why non-escaping is the default Before Swift 3 closure parameters escaped by default and `@noescape` opted out. **SE-0103 (Swift 3)** flipped it: a function-typed parameter is non-escaping unless marked `@escaping`. The guarantee "this closure will not be called after I return" buys several things: 1. **Simpler capture rules.** A non-escaping closure may refer to `self` implicitly, may capture an `inout` parameter, and may capture a struct's mutable `self` inside a `mutating` method. 2. **Cheaper code.** The Swift optimization tips note that a `var` captured by an escaping closure needs a heap box shared by the closure and its creator; a non-escaping closure gives the compiler room to avoid that work. 3. **Visible intent.** `@escaping` in a signature tells every caller that the closure — and everything it captures — may live on. Most closures passed to standard-library algorithms (`map(_:)`, `filter(_:)`, `sorted(by:)`) are non-escaping for exactly these reasons. ## The rules the compiler enforces | Situation | Result | |---|---| | Store a non-escaping parameter in a property | error: assigning non-escaping parameter … to an '@escaping' closure | | Escaping closure uses a class property without `self.` | error: reference to property … requires explicit use of 'self' | | Escaping closure writes a property in a struct's `mutating` method | error: escaping closure captures mutating 'self' parameter | | Escaping closure captures an `inout` parameter | error: escaping closure captures 'inout' parameter | | Write `@escaping` on an optional closure parameter | error: closure is already escaping in optional type argument | The last row surprises people: a parameter typed `((String) -> Void)?` is **already escaping**, because the function type sits inside `Optional` rather than being the parameter's own type. You can store it without any attribute, and writing `@escaping` there is an error. ## self inside an escaping closure For a class, an escaping closure that touches `self` keeps the instance alive for as long as the closure lives. Swift therefore makes the capture visible: you must write `self.x`, or put `self` in the capture list (`{ [self] in x = 100 }`), or capture it weakly with `[weak self]`. Whether that capture becomes a strong reference cycle is a question of who holds the closure — covered with ARC and reference cycles. For a struct or enum, an escaping closure can read `self`, but it cannot capture a **mutable** `self` inside a `mutating` method: value types do not allow shared mutation, so the compiler rejects it. The usual fix is to copy the values the closure needs into its capture list. ## Closure expressions and local bindings Whether a closure expression escapes depends on where it ends up. The language reference says a closure expression is non-escaping only if it is called immediately or passed as a non-escaping argument; otherwise it is escaping. Binding a closure to a local `let f = { … }` therefore produces an escaping closure. ## Bridging the rare mismatch Sometimes you hold a non-escaping closure and must pass it to an API that demands `@escaping`, although you know it will finish before you return. `withoutActuallyEscaping(_:do:)` gives you an escapable copy for the duration of its body; storing or calling that copy after the function returns is **undefined behavior**, so it is a tool for narrow, provable cases, not a way to silence the compiler. ## Reading @escaping in review - An `@escaping` parameter is a promise that the closure, and everything it captures, may outlive the call; check what it captures. - In a class, look for `self.` or a capture list inside the closure: that is where an object's lifetime gets extended. - If a function calls its closure only before returning, drop `@escaping` so callers get the simpler rules. - Remember that a closure parameter of optional type escapes without saying so in the signature.

  • In a Swift struct's mutating method, what happens when a closure that changes a property is passed to an @escaping parameter?
    Compilation fails with `escaping closure captures mutating 'self' parameter`. Inside a `mutating` method `self` is an `inout` value, and an escaping closure could write to it after the method returned, which value types forbid. Copy the needed values into a capture list, or redesign so the closure does not mutate the struct.
  • In Swift, when is `withoutActuallyEscaping(_:do:)` the right tool?
    When you hold a non-escaping closure, must pass it to an API whose parameter is `@escaping`, and can prove the closure finishes before your function returns. The escapable copy is valid only inside the `do` body; storing or calling it afterwards is undefined behavior.
  • In Swift, why can a parameter typed `((String) -> Void)?` be stored without @escaping?
    The non-escaping default applies to a parameter whose own type is a function type. Wrapped in `Optional`, the function type is a payload, which is always escaping, so it can be stored freely, and writing `@escaping` there is rejected with `closure is already escaping in optional type argument`.

  • @escaping makes the closure run on a background thread.
  • Marking a closure @escaping creates a retain cycle by itself.
  • Closure parameters escape by default and @noescape opts out.
  • An optional closure parameter needs @escaping before it can be stored.
  • A non-escaping closure cannot refer to self at all.