Swift variable name with ` (backtick)
Solution 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`
andx
have the same meaning.
In your example, default
is a Swift reserved keyword, that's why backticks are needed.
Solution 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]
Solution 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!"