← Back to Swift Course | Chapter 7: Closures | Lesson 3 of 6

Capturing Values

Capturing means a closure remembers and holds onto variables from where it was created, even after that place in the code has finished running.

Capturing a Variable

A closure automatically captures any variables it uses from its enclosing scope, keeping them alive and accessible even after that scope finishes.

Example: Capturing a Variable

markup
func makeIncrementer(incrementAmount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += incrementAmount
        return total
    }
    return incrementer
}
let incrementByTwo = makeIncrementer(incrementAmount: 2)
print(incrementByTwo())
print(incrementByTwo())
print(incrementByTwo())

Independent Captures per Closure Instance

Each call that creates a new closure gets its own independent captured storage, so separate closures don't interfere with each other.

Example: Independent Captures per Closure Instance

markup
func makeIncrementer(incrementAmount: Int) -> () -> Int {
    var total = 0
    return {
        total += incrementAmount
        return total
    }
}
let counterA = makeIncrementer(incrementAmount: 1)
let counterB = makeIncrementer(incrementAmount: 10)
print(counterA())
print(counterB())
print(counterA())
Common Mistakes
  1. Assuming a captured variable is copied at the moment of closure creation; in Swift, closures capture references and see later mutations.
  2. Being surprised that two closures created from the same function share the same captured variable's storage.
  3. Not realizing capturing a large object in a long-lived closure can keep it alive in memory longer than expected.
Chapter Summary
  • A closure captures variables and constants from its surrounding context by reference.
  • Because of capturing, a closure can still access and modify a variable after its original scope has ended.
  • Multiple closures created in the same context can share the same captured variable.
  • This capturing behavior is what makes closures useful for things like counters and callbacks.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.