Using Capture Lists in Swift

Are your closures capturing values?

Steven Curtis
The Startup

--

We want to use closures, and you might have seen [weak self] written when we create a closure.

Photo by David Ballew on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Some knowledge of closures would be helpful (Guide HERE)

Terminology

Capture lists: The list of values that you want to remain unchanged at the time the closure is created.

Capturing values: If you use external values inside your closure, Swift stores them alongside the closure. This way they persist even when the external part of the code no longer exists.

Closure: A self-contained block of functionality that can be passed around

The common use of capture lists

You may well have seen something that looks like the following (yes, you won’t print out a view, but still…here is the example…)

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
print (self?.view)
}
}
}

--

--