startupthekid startupthekid - 11 months ago 33
Swift Question

Capturing `self` within willSet

If I have a collection view delegate helper class with a property that looks like:

weak var delegate: UICollectionViewDelegate? {
willSet {
self.collectionView?.delegate = newValue

ever be captured inside the

Unlike other blocks, you can't do
[unowned self]
[weak self]
on the will set block. In cases where I had
collectionView?.delegate =
and self.collectionView?.delegate =
was always called, indicating to me that it doesn't make a difference whether or not
self` is used inside a setter block.


It is just a property observer, not a block which means it doesn't retain/copy/capture any object so you can safely use self in there.

By the way, I would implement getter and setter for that variable instead because you defined it just to be able to update the collectionView's delegate property:

weak var delegate: UICollectionViewDelegate? {
  get {
    return self.collectionView?.delegate
  set {
    self.collectionView?.delegate = newValue