I want to understant self
in Swift closure.
For Ex -
() -> Void = { [weak self] in
guard let `self` = self else {
self.callMethod2()
}
self.callMethod3()
}
Why we use backtick here? Is it good programming practice? How self is weakly captured here?
Swift 4.2 recently adopted a proposal to add this to the language:
guard let self = self else { return }
The proposed solution entails allowing self to be upgraded from a weak reference to a strong reference using optional binding.
For more details refer swift evolution proposal SE-0079
self
is a reserved word in Swift. Since you're creating a new local var called self you need to mark it with back-ticks, as explained in the link from rmaddy.
Note that the usual convention for mapping weak self to a strong var is to use the name strongSelf
:
() -> Void = { [weak self] in
guard let strongSelf = self else {
//your code to call self.callMethod2() can't succeed inside the guard (since in that case weak self is nil)
//self.callMethod2()
return //You must have a statement like return, break, fatalEror, or continue that breaks the flow of control if the guard statement fails
}
strongSelf.callMethod3()
}
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