Arrays keep ordered values. You can read elements by position and combine them with loops or arithmetic.

Read indexed values

firstScore
arrays.swift
Replay: real traced execution (multi-file project)
let firstScore = 7
let scores = [firstScore, 9, 6]
let first = scores[0]
let last = scores[2]
let total = first + last
print("first=\(first)")
print("total=\(total)")
let firstScore = 4
let scores = [firstScore, 9, 6]
let first = scores[0]
let last = scores[2]
let total = first + last
print("first=\(first)")
print("total=\(total)")
let firstScore = 10
let scores = [firstScore, 9, 6]
let first = scores[0]
let last = scores[2]
let total = first + last
print("first=\(first)")
print("total=\(total)")
  1. firstScore ← 7, scores ← [7, 9, 6], first ← 7, last ← 6, total ← 13

    1let firstScore→ 7 = 7  //@firstScore=4, 102let scores→ [7, 9, 6] = [firstScore7, 9, 6]3let first→ 7 = scores[0]74let last→ 6 = scores[2]65let total→ 13 = first7 + last66print("first=\(first7)")7print("total=\(total13)")
    outputfirst=7
    total=13
  1. firstScore ← 4, scores ← [4, 9, 6], first ← 4, last ← 6, total ← 10

    1let firstScore→ 4 = 42let scores→ [4, 9, 6] = [firstScore4, 9, 6]3let first→ 4 = scores[0]44let last→ 6 = scores[2]65let total→ 10 = first4 + last66print("first=\(first4)")7print("total=\(total10)")
    outputfirst=4
    total=10
  1. firstScore ← 10, scores ← [10, 9, 6], first ← 10, last ← 6, total ← 16

    1let firstScore→ 10 = 102let scores→ [10, 9, 6] = [firstScore10, 9, 6]3let first→ 10 = scores[0]104let last→ 6 = scores[2]65let total→ 16 = first10 + last66print("first=\(first10)")7print("total=\(total16)")
    outputfirst=10
    total=16

Follow the Array

  1. firstScore starts at 7.
  2. scores becomes [7, 9, 6].
  3. first = scores[0] reads 7.
  4. last = scores[2] reads 6.
  5. total = first + last becomes 13, so the program prints first=7 and total=13. | firstScore | scores | first | last | total | | --- | --- | --- | --- | --- | | 4 | 4, 9, 6 | 4 | 6 | 10 | | 7 | 7, 9, 6 | 7 | 6 | 13 | | 10 | 10, 9, 6 | 10 | 6 | 16 |
array index Swift arrays are zero-indexed, so `scores[0]` is the first value.

Exercise: arrays.swift

Reproduce first=7 and total=13, then try firstScore 4 and 10 and predict each total.