Stats

Contributors: 18 Saturday, November 12, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

String & Character Literals

Download swift eBook

Example

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

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 for your type.

3.0

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.

Special Characters

Certain characters require a special escape sequence to use them in string literals:

CharacterMeaning
\0the null character
\\a plain backslash, \
\ta tab character
\va vertical tab
\ra carriage return
\na 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!"