Arrays
7 min · Swift
Hold many values under one name, and reach for the one you want.
Enemy 1 of 5
So far every variable has held a single value. An Array holds several values in order under one name, written inside square brackets and separated by commas: ["apple", "banana", "cherry"]. You reach into an array with a position, counting from 0 rather than 1 — fruits[0] is the first item, fruits[1] the second, and so on. This zero-based counting is shared by almost every language you'll encounter (Rust, Kotlin, JavaScript, C), so it's worth getting comfortable with early.
Asking for an index that doesn't exist — like fruits[10] on a 3-item array — crashes the program at runtime rather than quietly returning nil or some placeholder value. This might feel harsh compared to some scripting languages, but it's a deliberate Swift design choice: a crash tells you immediately and loudly that something is wrong, rather than letting a silently invalid value drift further into your program and cause a confusing bug somewhere else later.
Loading editor...