Practical use of backticks in Swift

From this document :

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

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

Or, apparently, why do Swift designers allow this, and not just forbid us to use reserved words as identifiers?

+8
ios backticks identifier swift reserved-words
source share
2 answers

The most important use is interacting 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, this is a keyword in Swift, so you must tell the compiler that you do not want to use it as a keyword, but as an identifier, for example:

 `guard`() 

There are several keywords in Swift that are widely used as method / function names, for example. get and set . In many contexts, Swift can make a difference, but not always.

+13
source share

In some cases, using guard gives us a good example for this purpose. In such a scenerio, I need to check the lifetime of a variable variable if it no longer exists (current controller is freed). I do not want to execute the rest of the code.

  guard let `self` = self else { return } 
+4
source share

All Articles