0

I found this code in one of the old projects:

guard let `self` = self else {
     return .empty()
}

static let `default`: LayoutParameters = { ..some code.. }

I assume `` was used in older versions of the language. But I would like to know why it is used/was used. Also, I would like to know if there are any problems if do not change the code and "leave it as is" in the latest versions of Swift and Xcode. Does it work correctly? Should I replace this with

guard let self = self else ......
  • From the [documentation](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html): *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.* -- The first example is pointless because **the** `self` is meant – vadian Mar 02 '22 at 10:22
  • 1
    This is not a duplicate of the linked post. OP is asking about `\`self\`` not `self` – Leo Dabus Mar 02 '22 at 17:49
  • You should take a look at [Allow using optional binding to upgrade self from a weak to strong reference](https://github.com/apple/swift-evolution/blob/master/proposals/0079-upgrade-self-from-weak-to-strong.md) – Leo Dabus Mar 02 '22 at 17:50

2 Answers2

1

The Xcode IDE suggestion you using `` to help to use the same default key in Foundation SDK.

Example: default is a constant name in Foundation, if you want using default to create new variable name is default you need add ``.

But you using SwiftLint with default rules, Using a default contants name is a code smell.

ThuyTQ
  • 36
  • 3
1

self is a keyword and normally you cannot use keywords and reserved words in places outside their context. However, that sometimes creates problems. For that reason there is a special syntax to make the keyword to be a normal identifier, e.g.:

enum MyEnum: String {
   case `default`
}

(also see Swift variable name with ` (backtick))

Historically self was not allowed as as a constant name inside guard-let-else and therefore backticks were commonly (ab)used. They are no longer needed since Swift 4.2.

The code will still work correctly since you can wrap any identifier in backticks and it will just be a normal identifier.

Sulthan
  • 128,090
  • 22
  • 218
  • 270