Swift Academy · Lesson

Capturing Values by Reference

Understand how closures capture surrounding state.

Lesson 1 of 413 steps

Capturing Values by Reference is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Capturing Values by Reference” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Capturing Values by Reference”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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