Vocabulary for this course

The terms the chapters assume, in plain words. You can open this from any chapter.

array
An ordered list of values of one type, reached by position starting at zero.
block
A group of lines of code that run together, often inside curly brackets.
closure
A piece of code you can store in a value and pass to other code, remembered with the names around it.
compiler
The program that turns the code you write into something the machine can run, reporting mistakes before it does.
dictionary
A collection of key and value pairs, where each key appears once and finds its value.
enum
A type whose value is one of a fixed set of named cases, which may each carry extra data.
expression
A piece of code that produces a value, such as a sum or a call to a function.
function
A named piece of code that takes values and returns a result when called.
guard
A check that must pass before the code after it runs, leaving the scope early when it fails.
method
A function that belongs to a type and is called on a value of that type.
nil
The absence of a value, allowed only where a type says a value may be missing.
operator
A symbol such as plus or equals that combines values into a new one.
optional
A type that either holds a value or holds nothing, written with a question mark after the type.
optional chaining
Writing a question mark before something you reach into, so the result is nil when the value is missing.
property
A named value that belongs to a type or to one of its values.
protocol
A list of requirements that a type promises to meet, so code can work with any type that meets them.
scope
The region of code where a name can be used before it goes out of reach.
string interpolation
Putting a value inside text with a backslash and parentheses, so the value becomes part of the text.
struct
A type that groups related values and makes a copy whenever it is given another name or passed along.
subscript
A way to read or write an item in an array or dictionary by putting a key or position in square brackets.
type
What kind of value something is, such as a whole number or text, and what it can do.
unwrap
To get the value out of an optional after checking that something is there.

Swift from the ground up

Text and interpolation

Building text with a backslash and parentheses, joining strings, and the everyday string tools worth knowing.

Part 3 of 12

Beginner14 min readBack to Courses

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.

Output
Click "Run" to execute your code

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.

Output
Click "Run" to execute your code

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?