Text and interpolation
Building text with a backslash and parentheses, joining strings, and the everyday string tools worth knowing.
Text lives in double quotes
A String is a run of characters inside double quotes. You can join strings with a plus sign, so "Ada" + " " + "Lovelace" builds one longer piece of text.
Strings are counted by their characters. A full name gives its length with .count, which is a property rather than a function call.
Joining strings is not free. Each + builds a new string from both sides, so a long chain of plus signs makes several intermediate strings before the final one. For a sentence that cost is invisible, but a large document is better built by collecting the pieces in an array and joining them once.
Putting a value inside text
Interpolation drops a value into a string. You write a backslash, then a pair of parentheses around the thing you want, so a name and an age fit into one sentence without any plus signs.
The parentheses can hold more than a name: a sum, a function call, or a property works too, because Swift runs what is inside them and places the result in the text.
Interpolation is not magic; it asks the value for its textual description and places that in the string. A String gives its own characters, an Int gives its digits, and an optional gives a description that includes the word Optional. That is why interpolating a value that may be missing prints Optional("Ada"), and why the compiler warns you about it.
The string tools you will use
.uppercased() and .lowercased() change the case, .hasPrefix(...) asks how a string starts, and .contains(...) asks whether a piece appears anywhere inside.
.split(separator:) breaks text into a list of pieces, and the list answers .count. None of these change the original string. They hand back a new value, which is why the examples often print the result directly.
split(separator:) leaves out empty pieces by default. Two spaces in a row therefore produce no empty word between them, and a string that is only spaces splits to an empty list. That default suits ordinary prose, where repeated whitespace is an accident; when the empty pieces matter, pass omittingEmptySubsequences: false.
Counting characters, not bytes
count counts what a reader would call characters. An accented letter typed as one code point or as a letter plus a combining accent still counts once, because Swift groups the pieces into a single extended grapheme cluster.
That makes count safe for display, but it is not a measure of storage. If you need bytes, ask for utf8.count; if you need a position inside the text, use the string’s own indices rather than a whole number.
A single visible character can be built from several code points. An accented letter may be one point or a letter plus a combining mark, and a family emoji is a sequence joined by invisible characters. Swift groups all of those into one extended grapheme cluster, so count agrees with what a reader sees rather than with the number of bytes.
Escapes and multiline text
A backslash also marks characters that would otherwise end or confuse the string. The letter n after it starts a new line, t adds a tab, and a quote prints that quote instead of ending the string. To print the backslash itself, write two of them.
Triple quotes let a string span several lines, which keeps a long message readable in the source. Interpolation still works inside them, and the indentation before the closing delimiter is removed from every line.
A multiline string is still one value. The line breaks inside it are real characters, so printing it produces several lines, and count includes each break. The indentation rule removes only the whitespace that matches the closing delimiter, which is why the text can be indented with the code without gaining spaces.
Joining and measuring text
let first = "Grace"
let last = "Hopper"
print("\(first) \(last)")
print(first + " " + last)
print("Length:", (first + last).count)
let full = first + " " + last
print(full.uppercased())
print(full.hasPrefix("Grace"))
print(full.contains(" "))Three string mistakes are easy to make. "Total: " + 5 fails because + needs a String on both sides; interpolation is the way to put a number into text. .contains("swift") is case-sensitive, so lower-case the text first when case should not matter. And a double quote inside a string must be escaped as \", or it ends the string early.
Building a greeting
Run it and read how each line was put together. Then add a line that prints the full name with a comma between the two words.
Try these next
- Build one sentence with two interpolated values and no plus signs.
- Ask whether a title starts with a word in a different case, then lower-case it first and ask again.
- Split a sentence on its spaces, print each piece, then join the pieces with a dash.
A title becomes a slug
Run it and follow how one title produces a slug. Then change the title to a phrase with a different number of words and predict the slug and count before you run it.
Interpolation keeps the shape of a sentence and puts the values where they belong. Reading code full of plus signs is harder, so reach for the backslash and parentheses once a line has more than one value in it.
Check what you learned
One question at a time. A wrong answer explains itself — take another go.
Part 1 of 5
What does a backslash and parentheses do inside a string?
