0
0
Swiftprogramming~5 mins

Capturing values from context in Swift

Choose your learning style9 modes available
Introduction

Capturing values from context lets a small piece of code remember and use values from around it. This helps keep data handy without passing it again and again.

When you want a function inside another function to use variables from the outer function.
When you create a closure that needs to remember a value even after the original variable is gone.
When you want to keep track of a changing value inside a closure.
When you want to delay work but still use some data from now.
When you want to create a simple counter or accumulator using closures.
Syntax
Swift
let closure = { [captureList] in
    // code using captured values
}

The captureList is optional and lets you control how values are captured.

By default, Swift captures values strongly, but you can use weak or unowned to avoid strong references.

Examples
This closure captures x from the surrounding context and prints it.
Swift
var x = 10
let closure = { print(x) }
closure()
Here, x is captured by value at the time of closure creation, so it prints 5 even if x changes later.
Swift
var x = 5
let closure = { [x] in print(x) }
x = 10
closure()
This example shows capturing self weakly to avoid strong reference cycles.
Swift
class Person {
    var name = "Alice"
    lazy var greet = { [weak self] in
        print("Hello, \(self?.name ?? \"Guest\")")
    }
}
let p = Person()
p.greet()
Sample Program

This program creates a counter closure that captures count by reference. It increments and returns the count each time it is called.

Swift
func makeCounter() -> () -> Int {
    var count = 0
    let counter = {
        count += 1
        return count
    }
    return counter
}

let myCounter = makeCounter()
print(myCounter())
print(myCounter())
OutputSuccess
Important Notes

Capturing by value means the closure keeps a copy of the value at the time it is created.

Capturing by reference means the closure uses the current value, which can change later.

Use capture lists to avoid memory problems like strong reference cycles.

Summary

Closures can capture values from their surrounding context.

By default, Swift captures variables by reference, but you can capture by value using capture lists.

Capture lists help manage memory and control how values are stored inside closures.