Skip to content

Latest commit

 

History

History
39 lines (28 loc) · 1.85 KB

3.0 - Strings and Characters.md

File metadata and controls

39 lines (28 loc) · 1.85 KB

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.

Multi-line String Literals

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.

Initialization

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

Interpolation

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.

Previous Section | Back To Contents | Next Note