startupthekid startupthekid - 7 months ago 14
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
}
}


will
self
ever be captured inside the
willSet
block?

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

Answer

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
  }
}
Comments