带有`(反引号)的Swift变量名

use*_*732 17 swift alamofire

我正在浏览Alamofire源代码,并发现变量的哪个名称在此源文件中被反引号转义

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

    return SessionManager(configuration: configuration)
}()
Run Code Online (Sandbox Code Playgroud)

但是在使用变量的地方没有反引号.反叛的目的是什么?

Ort*_*kni 27

根据Swift文档:

要使用保留字作为标识符,请在其前后加上反引号.例如,class不是有效的标识符,但`class`是有效的.反引号不被视为标识符的一部分; `x`和x具有相同的含义.

在你的例子中,default是一个快速保留的关键字,这就是需要反引号的原因.


dfr*_*fri 8

在使用反引号正确声明保留字标识符之后,关于使用保留字标识符的示例答案附录。

反引号不视为标识符的一部分;x和x具有相同的含义。

意味着我们不必担心在标识符声明后使用反引号(但是我们可以):

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]
Run Code Online (Sandbox Code Playgroud)


Pat*_*erg 6

简单地说,通过使用反引号,您可以使用保留字来表示变量名等.

var var = "This will generate an error" 

var `var` = "This will not!"
Run Code Online (Sandbox Code Playgroud)