Reputation: 7476
I am doing the weak strong dance in swift this way:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { [weak self] in
guard let `self` = self else {
return
}
self.doSomething(1)
})
Before this, I was using strongSelf
instead of `self`. On a website I've seen that I can use this character ` .
But what does this character do in Swift? Without this I cannot assign to self. Why does this work? Is it a good practice to use it?
Upvotes: 10
Views: 4085
Reputation: 9337
A bit of an update (I will not refer here when to use it but rather how).
From Swift 4.2 the use should be like:
guard let self = self else { return }
Using `
is basically based on the compiler bug thus not advised.
For more information there is no better source than this. Explaining all reasoning behind and other considerations.
In short the above is more consistent with other cases seen in the code like:
if let myVariable = myVariable
So does not create confusion/discrepancies.
Upvotes: 17
Reputation: 3960
Presents a note that says the following:
If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with backticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.
EDIT:
The way I do this is using any other name for example strongSelf
like you previously did. Because in the end, both `self` and strongSelf
will be some variable to act upon. So I suggest if we can use some other variable name that is fine.
Upvotes: 9