What is the correct way of use strongSelf in swift?
Using strongSelf
is a way to check that self
is not equal to nil. When you have a closure that may be called at some point in the future, it is important to pass a weak
instance of self so that you do not create a retain cycle by holding references to objects that have been deinitialized.
{[weak self] () -> void in
if let strongSelf = self {
strongSelf.doSomething1()
}
}
Essentially you are saying if self no longer exists do not hold a reference to it and do not execute the action on it.
Swift 4.2 ð¸
guard let self = self else { return }
Ref: https://benscheirman.com/2018/09/capturing-self-with-swift-4-2/
Ref2: https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2
another way to use weak self
without using strongSelf
{[weak self] () -> void in
guard let `self` = self else { return }
self.doSomething()
}