Notes

Capture Lists

  • The lesson here is to consider carefully what you actually need to capture in your closure. Do you really need a reference to self? Or do you just need a reference to an object on self? If you can capture something more specific, you can often avoid dealing with weak or unowned references.
  • This code:
var thing = "cars"

let closure = { [thing] in
  print("I love \(thing)")
}

thing = "airplanes"

closure()

will print I love cars: The capture list creates a copy of thing when you declare the closure. This means that captured value doesn’t change even if you assign a new value to thing.

See also Can You Answer This Simple Swift Question Correctly? and Capture Lists

Links