-2

Normally when capturing reference to a property in a closure I would do something like this -

foo { [weak self] in
    self?.bar()
}

But I have also seen this written as -

foo { [bar] in
    bar()
}

What is meant by [bar] and how is this different from capturing a weak self?

Teddy K
  • 820
  • 1
  • 6
  • 17
  • 2
    It's a capture list. Please read the Swift language guide, cover to cover. It'll answer a whole load of questions like this. https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID57 – Alexander Nov 27 '19 at 18:37

2 Answers2

1

That [bar] part is a capture list.

It instructs the closures as how values should be captured. When you enter variables in the bracket right before the keyword in, the closure is no longer referencing the original variables, instead the closure creates its own copy within the closure block.

nodediggity
  • 2,458
  • 1
  • 9
  • 12
1

That's a capture list, which can be used to resolve strong reference cycles. If a closure captures variables by reference (which it does for all reference types), the closure could create a strong reference cycle by being the last object to hold a reference to the captured variable.

A weak reference means that it doesn't increase the reference count of the object, so if the last reference to an object is a weak one, its reference count is 0 and hence ARC will deallocate it. This is especially useful for escaping closures, whose lifetime might be longer than the lifetime of the referenced/captured objects and hence the closure could end up holding the last reference to the object and hence wouldn't allow ARC to deallocate it.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116