Strings operate in a similar way to how they do in other languages, and indeed, seem designed to work as an intuitive value-type (i.e. when you pass them to a function, you pass a copy of the value, not a reference to it). Thus, we can initialise them with literals, control their mutability using the var
and let
keywords and iterate over their characters using for-in
loops.
These are initialised with the """ syntax. e.g.
"""
The White Rabbit put on his spectacles. "Where shall I begin, \
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""
They can include line-breaks, unicode characters and tabbing as expected. Note that one does not have to explicitly escape " characters in a multi-line string.
An empty string can be initialised using either the empty String constructor or the "" syntax. The two below are equivalent:
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
Strings also allow interpolation for the dynamic creation of Strings. e.g.:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
The expression in a string interpolation cannot include unescaped backslashes, carriage returns or line feeds. They can, however, contain other values.