Closures and capture lists

Swift language Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

var count = 0
let a = { print(count) }
let b = { [count] in print(count) }
count = 5
a()
b()
Options
Hint 1 of 1

When is a capture list evaluated?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 5 then 0

Correct. a reads the live variable; b copied 0 when it was created.

Why not the others?
  • A 0 then 0. a captures the variable itself, so it sees the change to 5.
  • C 5 then 5. The capture list in b took a snapshot before the change.
  • D It doesn't compile. Both closures are valid.

30-second answer

Closures capture variables by reference, so they see later changes. A capture list ([count]) copies the current value when the closure is created. [weak self] captures a weak reference to break retain cycles. Escaping closures that capture self strongly can keep objects alive.

Practise saying it · 30 s. No recording, just a timer

Explain closure capture.

Say your answer out loud, then check which of these points you covered:

  • Captures by reference
  • Capture list snapshots
  • weak self breaks cycles

Deep dive

Capture lists are evaluated when the closure is created.

Value types captured without a capture list are shared via a box between the closure and its scope.

In Swift 6, captured variables in @Sendable closures must be immutable or Sendable.

[weak self] plus guard let self is the common pattern in async callbacks.

Common mistakes

  • Assuming closures copy variables.
  • Using [unowned self] where self may be gone.

Senior take & follow-ups

Seniors explain capture by reference and when a capture list snapshots.

Follow-up questions

Think of your answer first, then open the hint.

  1. When is [weak self] unnecessary?

    Show hint

    Non-escaping closures, and structured async work that finishes with self.

  2. What does [x = expensive()] do?

    Show hint

    Evaluates once at creation and captures the result.

Suggest a fix if something here is wrong or out of date.