10

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?

Infinite Possibilities
  • 7,415
  • 13
  • 55
  • 118
  • 1
    Related: http://stackoverflow.com/questions/31315358/use-reserved-keyword-a-enum-case. – Martin R Sep 07 '16 at 05:55
  • 1
    There is a proposal to allow `guard let self = self else { return }` in a future version of Swift: https://github.com/apple/swift-evolution/blob/master/proposals/0079-upgrade-self-from-weak-to-strong.md, and that your code works is considered a bug in the Swift compiler: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/007425.html. – Martin R Sep 07 '16 at 05:57
  • In practice the entire *guard dance* is pointless because GCD closures don't cause retain cycles. – vadian Oct 03 '18 at 11:04
  • Sure, thank you for notifying me. – Infinite Possibilities Aug 28 '20 at 08:42

2 Answers2

17

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.

Community
  • 1
  • 1
Julian
  • 9,299
  • 5
  • 48
  • 65
9

Swift Programming Language

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.

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
  • 1
    Thank you, that's a good information. Do we have any information about how good practice is it to use guard like I described? I see that Apple discourages to use keywords like this, but in this case it really seems to be a good solution. What do you think? – Infinite Possibilities Sep 07 '16 at 05:51