Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 146 ยท Functions and Closures

Escaping Closures and Autoclosures

Learn when Swift closures escape, why @escaping is required, how capture lists and [weak self] prevent reference cycles, and how @autoclosure delays evaluation in && and ??.

A closure is a piece of code you can hand to a function. Usually the function calls it right away and is done with it. But sometimes a function keeps the closure and calls it much later: after a timer fires, after a download finishes, after a button is tapped. That difference, "used now" versus "kept for later", is one of the most important ideas about closures, and Swift makes you state it in the code with the attribute @escaping.

This lesson explains what it means for a closure to escape, what the compiler checks, how to avoid the classic memory trap that escaping closures create, and how @autoclosure lets a caller write a plain expression that Swift quietly wraps in a closure. You should be comfortable with closures and function types first. Reference cycles are covered in depth in Memory Management with ARC; here you get the closure-specific part.

Non-escaping is the default

A closure parameter is non-escaping unless you say otherwise. That means the closure may only be used while the function is running. The function can call it, pass it along to another non-escaping parameter, or ignore it. It cannot store it, return it, or capture it in another closure that outlives the call.

Why does Swift insist? Because a non-escaping closure has a guaranteed lifetime, the compiler can skip some work: it does not need to allocate memory for the closure on the heap, it does not need reference counting for the values the closure captures, and it lets you write code without self. in many places. Non-escaping is cheaper and safer, so it is the default.

Swift A closure that is only used during the call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both repeatThree and measure call their closures and finish. Nothing escapes, so no attribute is needed.

What it means to escape

A closure escapes when it can still be called after the function that received it has returned. There are three common ways to let that happen:

  • store it in a property, array or dictionary,
  • return it from the function,
  • pass it to something else that runs later, such as Task or a dispatch queue.

If you try, the compiler stops you. This class collects button handlers, so it has to keep every closure it receives. The first version forgets @escaping on purpose.

Swift Storing a non-escaping closure (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports an error at the append line: converting non-escaping parameter 'handler' to generic parameter 'Element' may allow it to escape. Read it as: "you are putting something with a short lifetime into an array that lives longer." The fix is to promise Swift that this closure is allowed to outlive the call by marking the parameter type with @escaping:

Swift
func onTap(_ handler: @escaping () -> Void) {
    handlers.append(handler)
}
Swift The fix: @escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

@escaping goes in front of the function type, in the parameter list. It is a promise from the function to its callers: "I might keep this around." For callers it is a warning sign: closures passed here deserve a little more thought about what they capture.

Returning a closure is the other typical case. A function that builds and returns a function needs no attribute on the return type, since returned closures always escape, but the closure it returns usually captures local state:

Swift Returning a closure that remembers state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each call to makeCounter creates a fresh count. The returned closure keeps that variable alive, which is why the two counters do not interfere with each other. This is called capturing, and it is what makes escaping closures so useful and, as the next section shows, a bit dangerous.

You can tell from the function type whether a closure parameter escapes, but the call site looks identical. When reading unfamiliar code, check the declaration: an @escaping parameter means "this closure may run later."

Escaping closures and self

Inside a class, an escaping closure that uses a property or method of the instance must say self explicitly. That is not noise: it is a reminder that the closure now holds a strong reference to the object.

Swift Missing explicit self (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get reference to property 'ticks' in closure requires explicit use of 'self' to make capture semantics explicit. Write self.ticks += 1 and it compiles. (Non-escaping closures do not need self., which is another practical benefit of the default.) Structs are the exception: an escaping closure may capture a struct's self without the keyword, because a struct is copied into the closure, so no strong reference to a shared object is created.

The reference cycle trap

Here is the problem. Suppose an object stores a closure, and that closure uses self. Then:

  1. the object owns the closure (through the property),
  2. the closure owns the object (through its capture of self).

Neither can ever be freed, because each keeps the other's reference count above zero. This is a retain cycle, and Swift's memory management, ARC, does not clean it up. The memory leaks until the program ends. A deinit that never prints is the classic way to notice.

Swift A retain cycle through a stored closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The leaky screen never prints its deallocated line, because the closure it stores holds it. The tidy screen does, as soon as its block ends. The difference is the capture list [weak tidy] at the start of the closure.

Capture lists

A capture list sits between the opening brace and the parameters, in square brackets. It decides how each listed value is captured:

  • [weak x] captures a weak reference. The reference does not keep the object alive and becomes an optional that turns into nil once the object is gone. You must unwrap it.
  • [unowned x] captures an unowned reference. It does not keep the object alive either, but it is not optional: if the object is gone and you use it, the program traps. Use it only when the closure can never outlive the object.
  • [x] or [x = expression] captures a copy of the current value, instead of a live variable.

The third form matters even when no objects are involved. Normally a closure captures a variable itself, so later changes are visible. A capture list freezes the value at the moment the closure is created:

Swift Capturing a variable versus capturing its value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The [weak self] pattern

In real code you will meet [weak self] constantly. The usual shape is to capture weakly and then unwrap with guard let self:

Swift
func load() {
    service.fetch { [weak self] result in
        guard let self else { return }
        self.finish(with: result)
    }
}

If the object disappeared while the work was running, the closure simply returns. That is exactly right for things like screens that were dismissed. Notice guard let self with no right-hand side: this shorthand has worked since Swift 5.7.

Swift weak self in a delayed callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

When page is set to nil, the only strong reference disappears. The page is freed (page freed appears), and when the downloader finally calls the closure, the weak self is nil, so the closure takes the guard exit.

Do not add [weak self] everywhere out of habit. If a closure is not stored by the object it captures (for example it is non-escaping, or it runs once and is then released), there is no cycle. Reach for it when an object stores a closure that refers back to it, or when you want the work to stop caring about a dead object.

Autoclosures: delaying an expression

The second attribute in this lesson solves a different problem. Consider a logging function. The message can be expensive to build, and when logging is off, building it is wasted work:

TEXT
func log(_ message: String, enabled: Bool) { ... }
log(buildReport(), enabled: false)   // buildReport() still runs!

You could change the parameter to () -> String and make every caller write braces, but that is clumsy. @autoclosure lets the caller write a plain expression, and the compiler wraps it into a closure automatically. The expression then runs only if and when the function calls the closure.

Swift @autoclosure delays evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With enabled: false the text (building the message) never appears: the expression was never evaluated. With true it appears exactly once, when the function calls message().

An autoclosure parameter must have the type () -> T: no arguments, one result. The caller cannot tell by looking at the call, so use autoclosures sparingly and name the parameter clearly.

You already use autoclosures

The standard library relies on them for short-circuiting. The right-hand side of &&, || and ?? is an autoclosure, which is why it is only evaluated when needed:

Swift Short-circuiting is autoclosure in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

assert(_:_:) and precondition(_:_:) use the same trick for their condition and message. In a release build the assertion expression is not evaluated at all. Note that this program is compiled with -O, so assertions are removed: the message is never built.

Autoclosures that escape

An autoclosure is non-escaping by default. If a function wants to keep it, combine the two attributes as @autoclosure @escaping:

Swift
final class LazyBox<T> {
    private let make: () -> T
    init(_ make: @autoclosure @escaping () -> T) { self.make = make }
    func value() -> T { make() }
}
Swift @autoclosure @escaping storing a deferred value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The square is computed once, on first access, and then cached. This is the idea behind lazy properties.

Common mistakes

  • Forgetting that closures keep what they capture alive. Long-lived closures that capture big objects are a source of leaks and surprising lifetimes.
  • Using [unowned self] to silence a warning. If the object can die first, you trade a leak for a crash. Prefer [weak self] unless you can prove the ordering.
  • Capturing a loop variable or a var and expecting a snapshot. A plain capture shares the variable; use a capture list for a copy.
  • Making a parameter @escaping "just in case". It costs performance and forces callers to deal with self. Add it only when the compiler asks.
  • Overusing @autoclosure. Hiding a closure behind a normal-looking argument makes code harder to read. It shines for lazily evaluated conditions and messages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When must a closure parameter be marked @escaping?

    Parameters are non-escaping by default. If the closure is stored, returned or passed to something that runs later, it outlives the call and needs @escaping.
  2. 2. What creates a retain cycle in this code? screen.onClose = { print(screen.name) }

    The screen owns the closure through onClose and the closure owns the screen through its capture, so neither reference count can reach zero.
  3. 3. What does [weak self] in a capture list give you inside the closure?

    A weak reference does not keep the object alive, so it must be optional; unwrap it with guard let self or optional chaining.
  4. 4. What is printed? func f(_ x: @autoclosure () -> Int) { print("in f") } followed by f({ print("evaluating"); return 1 }())

    The argument is wrapped in a closure that f never calls, so the expression is never evaluated and only in f is printed.
  5. 5. Why does a && b() not call b() when a is false?

    The standard library declares the right operand of && and || as an @autoclosure, so it runs only if the left side does not already decide the result.

Summary

  • Closure parameters are non-escaping by default: they may only be used during the call.
  • Mark a parameter @escaping when the function stores it, returns it or passes it to code that runs later; the compiler tells you when you forget.
  • Escaping closures that use instance members in a class need an explicit self., as a reminder of the strong capture.
  • A stored closure that captures its owner creates a retain cycle; break it with a capture list such as [weak self] (optional) or [unowned self] (non-optional, crashes if the object is gone).
  • A capture list like [score] also freezes a copy of a value instead of sharing the variable.
  • @autoclosure wraps an argument expression in a closure so it runs only if the function calls it; &&, ||, ?? and assert work this way.
  • Use @autoclosure @escaping to store a deferred expression, and use both attributes sparingly.

Next: map, filter, reduce and Friends