Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical application of backticks in Swift

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?

like image 390
Luke Avatar asked Jul 22 '16 18:07

Luke


Video Answer


2 Answers

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.

like image 122
Sulthan Avatar answered Oct 16 '22 20:10

Sulthan


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
 }
like image 38
Ali Kıran Avatar answered Oct 16 '22 18:10

Ali Kıran