0Pricing
Swift Academy · Lesson

Capturing Values by Reference

Understand how closures capture surrounding state.

What Closures Capture

A closure captures the variables and constants from the surrounding scope that it references. Captured variables are held by reference, so the closure sees later changes.

Capturing a Constant

The closure remembers greeting even after the function returns:

func makeGreeter() -> () -> String {
    let greeting = "Hello"
    return { greeting }
}
let greet = makeGreeter()
print(greet())  // "Hello"

All lessons in this course

  1. Capturing Values by Reference
  2. Escaping Closures
  3. Capture Lists and Weak Self
  4. Autoclosures
← Back to Swift Academy