Swift variable name with ` (backtick) - swift

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

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.

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]

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

Related

Does TypeScript has variable names escaping feature like backticks in Scala for literal identifiers?

Does TypeScript has variable names escaping feature like backticks in Scala for literal identifiers:
`0029-otherwise-illegal-scala-literal`
See Scala explanation in Need clarification on Scala literal identifiers (backticks)
You can find the spec at https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#8.2
Section 2.2.2 tells you
The PropertyName production from the ECMAScript grammar is reproduced
below:
  PropertyName:    LiteralPropertyName    ComputedPropertyName
  LiteralPropertyName:    IdentifierName    StringLiteral
   NumericLiteral
  ComputedPropertyName:    [ AssignmentExpression ]
A property name can be any identifier (including a reserved word), a
string literal, a numeric literal, or a computed property name. String
literals may be used to give properties names that are not valid
identifiers, such as names containing blanks. Numeric literal property
names are equivalent to string literal property names with the string
representation of the numeric literal, as defined in the ECMAScript
specification.
This includes string literals.
You can declare a property as a string literal:
class MyClass {
"return" = 1;
}
you can access it with square brackets
let myinstance = new MyClass()
let one = myinstance["return"]

Multiline statement in Swift

I was working on a Swift tutorial and found that Swift has a strange way to handle multi-line statement.
First, I defined some extension to the standard String class:
extension String {
func replace(target: String, withString: String) -> String {
return self.stringByReplacingOccurrencesOfString(target, withString: withString)
}
func toLowercase() -> String {
return self.lowercaseString
}
}
This works as expected:
let str = "HELLO WORLD"
let s1 = str.lowercaseString.replace("hello", withString: "goodbye") // -> goodbye world
This doesn't work:
let s2 = str
.lowercaseString
.replace("hello", withString: "goodbye")
// Error: could not find member 'lowercaseString'
If I replace the reference to the lowercaseString property with a function call, it works again:
let s3 = str
.toLowercase()
.replace("hello", withString: "goodbye") // -> goodbye world
Is there anything in the Swift language specifications that prevent a property to be broken onto its own line?
Code at Swift Stub.
This is definitely a compiler bug. Issue has been resolved in Xcode 7 beta 3.
This feels like a compiler bug, but it relates to the fact that you can define prefix, infix, and postfix operators in Swift (but not the . operator, ironically enough). I don't know why it only gives you grief on the property and not the function call, but is a combination of two things:
the whitespace before and after the . (dot) operator for properties (only)
some nuance of this ever growing language that treats properties differently than function calls (even though functions are supposed to first class types).
I would file a bug to see what comes out of it, Swift is not supposed to by pythonic this way. That said, to work around it, you can either not break the property from the type, or you can add a white space before and after the . .
let s2 = str.lowercaseString
.replace("hello", withString: "goodbye")
let s3 = str
. lowercaseString
.replace("hello", withString: "goodbye")
Using semicolons is not mandatory in swift. And I think that the problems with multiline statements in swift are because of optional semicolons.
Note that swift does not support multiline strings. Check here: Swift - Split string over multiple lines
So maybe swift cannot handle multiline statements. I am not sure about this and this could be one of the reasons so I would appreciate if anyone else can help regarding this issue.

Can you declare strings as constants in swift?

Is let name = "string" valid swift code? I thought let only allows a variable to be a constant, but this is obviously type inferred as a string.
Ok, we need to make a distinction.
Mutability
You can declare a constant or a variable.
You declare a constant with the keyword let.
let thisIsNotGoingToChange = 1
thisIsNotGoingToChange = 2 // <- error
You declare a variable with the keyword var:
var thisCouldChange = 1
thisCouldChange = 2 // no problem
So when you ask "Can you declare let variable as a string in swift?" I have to reply: "No".
Because let is a constant and cannot be a variable.
Type
Both constants (let) and variables (var) must have a type and it can be a String.
let thisIsAConstant = "thisStringWillNotChange"
var thisIsAVariable = "thisStringCouldChange"
Hope it helps.
Predefined String values could be defined by let , here is the example and reference for further information.
The: let keyword defines a constant:
let someString = "Some string literal value"
The someString cannot be changed afterwards.
The var defines an ordinary variable:
What is interesting:
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
Another strange feature:
You can use almost any character you like for constant and variable names, including Unicode characters:
let 🐶🐮 = "yeap!"
To make it short, let is used to define constants and var to define variables
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

Double underscore prefix in Swift variables

In the Advanced Swift talk, the generated code for an for loop is described as:
var __g: Generator = mySequence.generate()
while let x = __g.next() {
// iterations here
}
Does the underscore prefix have some specific meaning?
No, the underscore- and double-underscore-prefixes have no specific meaning in Swift. They conventionally imply "private" or "internal" declarations, but you can define variables beginning with as many underscores as you like.

Pattern variable binding cannot appear in an expression

I've been looking at The Swift Programming Language guide provided by apple.
Following sample is from the book:
class HTMLElement {
let name :String;
let text: String?;
#lazy var asHTML : () -> String = {
if let text = self.text {
return "<\(self.name)>\(self.text)</\(self.name)>";
} else {
return "<\(self.name) />"
}
}
}
I incorrectly wrote the closure as follow:
#lazy var asHTML : () -> String = {
if (let text = self.text) {
return "<\(self.name)>\(self.text)</\(self.name)>";
} else {
return "<\(self.name) />"
}
}
Notice the parentheses around let text = self.text and compiler complain about:
Pattern variable binding cannot appear in an expression
Just wondering what does Pattern Variable Binding mean, and why it cannot appear in an expression?
A "pattern variable binding" is the thing you're doing, i.e. using let in the middle of some code, not at the top level of a file or enum or struct or class as a way of declaring a constant variable.
What makes it an expression is the parentheses. You've cut the "let" expression off from its surroundings and asked for evaluation of it as an expression separately. But you can't do that: you can't say "let" just anywhere.
Another way of looking at it is simply this: if let is a fixed meaningful pattern, where the condition is an Optional being evaluated into a constant for use inside the if-code. The parenthesis broke up the pattern.
The pattern is called a binding because you're defining this name very temporarily and locally, i.e. solely down into the if-code. I think it goes back to LISP (at least, that's where I've used "let" this way in the past).