Swift Arrays
Grow an array and combine its values with reduce.
On this page
Swift basics.
- Grow an array and combine its values with reduce.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
An array stores ordered values of one type. Declare it with var if you want to change it, since let makes it a constant. append adds an element at the end and count returns the length.
reduce starts from an initial result, here 0, and combines it with each element using the given function. Passing the operator + works because it is just a function of two numbers.
Code example
var scores = [82, 91, 76]
scores.append(95)
let total = scores.reduce(0, +)
print(scores.count, total)4 344
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
var scores = [82, 91, 76]scores.append(95)let total = scores.reduce(0, +)print(scores.count, total)Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| A mutable array of Int. | scores = [82, 91, 76] | — | |
| Append a fourth value. | scores = [82, 91, 76, 95] | — | |
| Start at 0 and add each element. | total = 344 | — | |
| print separates its arguments with a space. | total = 344 | 4 344 |
Behind the scenes
How Swift processes this code
Swift compiles the program; its top-level statements run in source order.
Cost and common mistakes
append is amortized O(1); reduce is O(n) time and O(1) space.
- Calling append on an array declared with let is a compile error.
- Reading an index beyond the end crashes the program at runtime.
Try it yourself
Use max() to find the highest score.
Reveal answer and reasoning
scores.max() returns an optional, Optional(95), because an empty array has no maximum.