In Objective-C in non-trivial blocks I noticed usage of weakSelf/strongSelf.
What is the correct way of usage strongSelf in Swift? Something like:
if let strongSelf = self {
strongSelf.doSomething()
}
So for each line containing self in closure I should add strongSelf check?
if let strongSelf = self {
strongSelf.doSomething1()
}
if let strongSelf = self {
strongSelf.doSomething2()
}
Is there any way to make aforesaid more elegant?
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.
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
Your use of strongSelf
appears to be directed at only calling the doSomethingN()
method if self
is not nil. Instead, use optional method invocation as the preferred approach:
self?.doSomethingN()
another way to use weak self
without using strongSelf
{[weak self] () -> void in
guard let `self` = self else { return }
self.doSomething()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With