Search code examples
swiftweak-references

How to reference weak in 1 line?


How can I make a weak reference without declaring an extra variable?

E.g. how can I write this in 1 line:

    weak var weakSelf = self
    self.interactivePopGestureRecognizer?.delegate = weakSelf

Solution

  • Whether a property is weak or strong is an attribute of the property. It isn't an attribute of the value being assigned to it.

    In your case, the delegate property of your interactivePopGestureRecognizer must be declared as weak for this to do anything useful.

    In the class UIGestureRecognizer, the delegate is indeed weak:

    @property(nullable,nonatomic,weak) id <UIGestureRecognizerDelegate> delegate; // the gesture recognizer's delegate
    

    So you just need to do:

    self.interactivePopGestureRecognizer?.delegate = self