Swift variable name with ` (backtick)

血红的双手。 提交于 2019-11-26 22:00:21

问题


I was browsing Alamofire sources and found variable which name 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?


回答1:


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.




回答2:


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]



回答3:


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!"


来源:https://stackoverflow.com/questions/41503740/swift-variable-name-with-backtick

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!