Practical application of backticks in Swift
Asked Answered
T

2

19

From this document:

To use a reserved word as an identifier, put a backtick (`) before and after it.

I'm curious about the practical application of this. When would you actually want to name something `class`, `self`, etc.?

Or, relatedly, why did the designers of Swift allow this, rather than just forbidding us from using reserved words as identifiers?

Trstram answered 22/7, 2016 at 18:52 Comment(2)
The designers of swift are everyone. It's open source and heavily influenced by the community. So there must have been enough evidence to support the possibility of someone wanting to do that.Sebaceous
This feature was useful to me when automatically producing Swift code from data that wasn’t designed for that use. For instance, creating a struct corresponding to an XML element which happened to have an attribute named “extension”: struct Filename { var ˋextensionˋ = "txt" }. A standard way of dealing with this is better than having to define my own non-failproof scheme, for instance using “_extension”.Overgrowth
C
25

The most important usage is the interaction with other languages that have different keywords.

From Swift you can call C and Obj-C functions.

Now, consider for example that you need to call a C function called guard. However, that's a keyword in Swift, therefore you have to tell the compiler that you don't want to use it as a keyword but as an identifier, e.g.:

`guard`()

There are multiple keywords in Swift that are widely used as method/function names, e.g. get and set. For many contexts Swift is able to figure out the difference but not always.

Commonplace answered 22/7, 2016 at 19:3 Comment(0)
P
7

In some cases using guard give us nice example for this purpose.In such scenario I need check self variable life time if not exist anymore (current controller deallocated) I don't want to execute rest of code.

 guard let `self` = self else {
        return
 }
Paean answered 22/7, 2016 at 19:0 Comment(3)
I think a cleaner way than your answer is: guard let _ = self else { return }Arbitrator
By the way, it has been officially said that this application of backtics is a bug.Commonplace
Backticks in this case are no longer required since Swift 4.Commonplace

© 2022 - 2024 — McMap. All rights reserved.