Swift Arrays

Grow an array and combine its values with reduce.

Swift
var scores = [82, 91, 76]
scores.append(95)
let total = scores.reduce(0, +)
print(scores.count, total)
Output
4 344

Explanation

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.

Explore the dry run
Guided walkthroughReady
1var scores = [82, 91, 76]
2scores.append(95)
3let total = scores.reduce(0, +)
4print(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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

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.

Further reading