40

I was browsing Alamofire sources and found a variable name that is backtick escaped in this source file

open static let `default`: SessionManager = {
    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders

    return SessionManager(configuration: configuration)
}()

However in places where variable is used there are no backticks. What's the purpose of backticks?

Removing the backticks results in the error:

Keyword 'default' cannot be used as an identifier here

pkamb
  • 33,281
  • 23
  • 160
  • 191
user3237732
  • 1,976
  • 2
  • 21
  • 28

3 Answers3

60

According to the Swift documentation :

To use a reserved word as an identifier, put a backtick (`)before and after it. For example, class is not a valid identifier, but `class` is valid. The backticks are not considered part of the identifier; `x` and x have the same meaning.

In your example, default is a Swift reserved keyword, that's why backticks are needed.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
10

Example addendum to the accepted answer, regarding using reserved word identifiers, after they have been correctly declared using backticks.

The backticks are not considered part of the identifier; `x` and x have the same meaning.

Meaning we needn't worry about using the backticks after identifier declaration (however we may):

enum Foo {
    case `var`
    case `let`
    case `class`
    case `try`
}

/* "The backticks are not considered part of the identifier; 
    `x` and x have the same meaning"                          */
let foo = Foo.var
let bar = [Foo.let, .`class`, .try]
print(bar) // [Foo.let, Foo.class, Foo.try]
Aleksa
  • 529
  • 4
  • 16
dfrib
  • 70,367
  • 12
  • 127
  • 192
8

Simply put, by using backticks you are allowed to use reserved words for variable names etc.

var var = "This will generate an error" 

var `var` = "This will not!"
NSNoob
  • 5,548
  • 6
  • 41
  • 54
Patrik Forsberg
  • 622
  • 9
  • 8