Loops can visit each value in a collection and build a result.

Accumulate values

bonus
collection_iteration.swift
Replay: real traced execution (multi-file project)
let bonus = 1
let baseScores = [2, 4, 6]
var total = 0

for score in baseScores {
    total = total + score + bonus
}

print("bonus=\(bonus)")
print("total=\(total)")
let bonus = 0
let baseScores = [2, 4, 6]
var total = 0

for score in baseScores {
    total = total + score + bonus
}

print("bonus=\(bonus)")
print("total=\(total)")
let bonus = 3
let baseScores = [2, 4, 6]
var total = 0

for score in baseScores {
    total = total + score + bonus
}

print("bonus=\(bonus)")
print("total=\(total)")
  1. bonus ← 1, baseScores ← [2, 4, 6], total ← 0

    1let bonus→ 1 = 1  //@bonus=0, 32let baseScores→ [2, 4, 6] = [2, 4, 6]3var total→ 0 = 0
  2. total ← 3

    pass 1 of 3
    5for score2 in baseScores[2, 4, 6] {6    total→ 3 = total + score2 + bonus17}
    All 3 passes — pass 1 is the card above
    passscoretotal
    120 3
    243 8
    368 15
  3. print("bonus=\(bonus)")

    9print("bonus=\(bonus1)")10print("total=\(total15)")
    outputbonus=1
    total=15
  1. bonus ← 0, baseScores ← [2, 4, 6], total ← 0

    1let bonus→ 0 = 02let baseScores→ [2, 4, 6] = [2, 4, 6]3var total→ 0 = 0
  2. total ← 2

    pass 1 of 3
    5for score2 in baseScores[2, 4, 6] {6    total→ 2 = total + score2 + bonus07}
    All 3 passes — pass 1 is the card above
    passscoretotal
    120 2
    242 6
    366 12
  3. print("bonus=\(bonus)")

    9print("bonus=\(bonus0)")10print("total=\(total12)")
    outputbonus=0
    total=12
  1. bonus ← 3, baseScores ← [2, 4, 6], total ← 0

    1let bonus→ 3 = 32let baseScores→ [2, 4, 6] = [2, 4, 6]3var total→ 0 = 0
  2. total ← 5

    pass 1 of 3
    5for score2 in baseScores[2, 4, 6] {6    total→ 5 = total + score2 + bonus37}
    All 3 passes — pass 1 is the card above
    passscoretotal
    120 5
    245 12
    3612 21
  3. print("bonus=\(bonus)")

    9print("bonus=\(bonus3)")10print("total=\(total21)")
    outputbonus=3
    total=21

Add Each Score

  1. baseScores starts as [2, 4, 6].
  2. bonus is 1.
  3. The loop adds each score plus the bonus.
  4. The final total is 15. | Score | Added with bonus 1 | Running total | | --- | --- | --- | | 2 | 3 | 3 | | 4 | 5 | 8 | | 6 | 7 | 15 |
iteration A `for` loop over an array handles each element in order. The running total shows how repeated updates build a final result.

Exercise: collection_iteration.swift

Loop through scores, add each score plus a bonus, and print the final total