String literals in Swift are delimited with double quotes ("
):
let greeting = "Hello!" // greeting's type is String
Characters can be initialized from string literals, as long as the literal contains only one grapheme cluster:
let chr: Character = "H" // valid
let chr2: Character = "π" // valid
let chr3: Character = "abc" // invalid - multiple grapheme clusters
String interpolation allows injecting an expression directly into a string literal. This can be done with all types of values, including strings, integers, floating point numbers and more.
The syntax is a backslash followed by parentheses wrapping the value: \\(value)
. Any valid expression may appear in the parentheses, including function calls.
let number = 5
let interpolatedNumber = "\\(number)" // string is "5"
let fortyTwo = "\\(6 * 7)" // string is "42"
let example = "This post has \\(number) view\\(number == 1 ? "" : "s")"
// It will output "This post has 5 views" for the above example.
// If the variable number had the value 1, it would output "This post has 1 view" instead.
For custom types, the default behavior of string interpolation is that "\\(myobj)"
is equivalent to String(myobj)
, the same representation used by print(myobj)
. You can customize this behavior by implementing the [CustomStringConvertible
protocol](https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_CustomStringConvertible_Protocol/index.html) for your type.
For Swift 3, in accordance with SE-0089, String.init<T>(_:)
has been renamed to String.init<T>(describing:)
.
The string interpolation "\\(myobj)"
will prefer the new String.init<T: LosslessStringConvertible>(_:)
initializer, but will fall back to init<T>(describing:)
if the value is not LosslessStringConvertible
.
Certain characters require a special escape sequence to use them in string literals:
Character | Meaning β | β \\0
| the null character \\\\
| a plain backslash, \\\\
\\t
| a tab character \\v
| a vertical tab \\r
| a carriage return \\n
| a line feed (βnewlineβ) \\"
| a double quote, "
\\'
| a single quote, \\'
\\u{n}
| the Unicode code point n (in hexadecimal)
Example:
let message = "Then he said, \\"I \\u{1F496} you!\\""
print(message) // Then he said, "I π you!"