Capture List

Janvi Arora
2 min readMar 16, 2023

--

A capture list is a feature in Swift that allows you to capture and store a reference to a variable or constant from the surrounding context within a closure. The capture list specifies which variables should be captured and how they should be captured.

In Swift, a closure can capture variables from its surrounding context, such as a function or method. By default, these variables are captured as strong references, which means that the closure retains a strong reference to the captured variable, and the variable is not deallocated until the closure is released.

However, in some cases, you may want to avoid retain cycles or manage memory more carefully. This is where the capture list comes in.

A capture list is a comma-separated list of variables or constants enclosed in square brackets [], followed by the capture mode. The capture mode specifies how the variable or constant should be captured:

  • weak: The closure captures the variable as a weak reference, which means that the variable may be deallocated before the closure is released. To use a weak reference, prefix the variable or constant with weak in the capture list.
  • unowned: The closure captures the variable as an unowned reference, which means that the variable is assumed to always have a value and will not be deallocated before the closure is released. To use an unowned reference, prefix the variable or constant with unowned in the capture list.

Here’s an example of a closure that uses a capture list to capture a variable as a weak reference:

class ExampleClass {
var value = 42
lazy var lazyClosure: () -> Int = { [weak self] in
return self?.value ?? 0
}
}

In this example, the lazyClosure property is a closure that captures self as a weak reference. This means that if the instance of ExampleClass is deallocated before the closure is released, the closure will automatically set self to nil. The closure returns the value of the value property of the instance, or 0 if self is nil.

By using a capture list, you can manage memory more carefully and avoid retain cycles in your closures.

--

--

No responses yet