0Pricing
Swift Academy · Lesson

Capturing Values by Reference

Understand how closures capture surrounding state.

Capturing Values by Reference is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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"

Capturing a Variable by Reference

Because count is a var, the closure mutates the same storage across calls:

func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}
let next = makeCounter()
print(next(), next(), next())  // 1 2 3

Shared Storage

Two closures can capture the same variable and see each other changes:

func makePair() -> (() -> Void, () -> Int) {
    var value = 0
    let inc = { value += 1 }
    let read = { value }
    return (inc, read)
}
let (inc, read) = makePair()
inc(); inc()
print(read())  // 2

Capture Reflects Later Changes

The closure reads the variable current value at call time, not its value when the closure was created:

var message = "first"
let show = { print(message) }
message = "second"
show()  // "second"

Reference vs Value Capture

By default a mutable variable is captured by reference. If you want a frozen copy of its value at creation time, list it in a capture list like [x].

Freezing a Value

A capture list copies the value immediately:

var n = 10
let frozen = { [n] in n }   // copies 10 now
n = 99
print(frozen())  // 10

Each Closure, Independent State

Each call to the factory makes a fresh captured variable:

func counter() -> () -> Int {
    var c = 0
    return { c += 1; return c }
}
let a = counter(), b = counter()
print(a(), a(), b())  // 1 2 1

Capturing in a Loop

Without care, closures in a loop can share the same variable. Use a capture list to snapshot per iteration:

var closures: [() -> Int] = []
for i in 1...3 {
    closures.append { [i] in i }
}
print(closures.map { $0() })  // [1, 2, 3]

Capturing self in a Method

A closure created inside a method captures the surrounding instance, letting it read and mutate properties later:

class Bank {
    var balance = 0
    func deposit() -> () -> Void {
        return { self.balance += 10 }
    }
}
let bank = Bank()
let add = bank.deposit()
add(); add()
print(bank.balance)  // 20

Why It Matters

Capture-by-reference powers counters, accumulators, and stateful callbacks — but it also means a closure can keep objects alive, which we manage with capture lists next.

func accumulator() -> (Int) -> Int {
    var total = 0
    return { total += $0; return total }
}
let add = accumulator()
print(add(10), add(5))  // 10 15

Quick Check

How is a mutable variable captured by a closure by default?

Recap

You learned capture semantics:

  • Closures capture referenced variables from their scope
  • Mutable vars are captured by reference — changes and mutations are shared
  • A capture list [x] freezes a value copy at creation
  • This powers counters and stateful callbacks

Next: escaping closures.

Frequently asked questions

Is the “Capturing Values by Reference” lesson free?

Yes — the full text of “Capturing Values by Reference” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Capturing Values by Reference”?

Understand how closures capture surrounding state. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Capturing Values by Reference” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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