Collections
Collection Iteration
Loops can visit each value in a collection and build a result.
Accumulate values
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)")
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 = 0total ← 3
pass 1 of 35for score2 in baseScores[2, 4, 6] {6 total→ 3 = total + score2 + bonus17}All 3 passes — pass 1 is the card above pass scoretotal1 2 0 → 3 2 4 3 → 8 3 6 8 → 15 print("bonus=\(bonus)")
9print("bonus=\(bonus1)")10print("total=\(total15)")outputbonus=1 total=15
bonus ← 0, baseScores ← [2, 4, 6], total ← 0
1let bonus→ 0 = 02let baseScores→ [2, 4, 6] = [2, 4, 6]3var total→ 0 = 0total ← 2
pass 1 of 35for score2 in baseScores[2, 4, 6] {6 total→ 2 = total + score2 + bonus07}All 3 passes — pass 1 is the card above pass scoretotal1 2 0 → 2 2 4 2 → 6 3 6 6 → 12 print("bonus=\(bonus)")
9print("bonus=\(bonus0)")10print("total=\(total12)")outputbonus=0 total=12
bonus ← 3, baseScores ← [2, 4, 6], total ← 0
1let bonus→ 3 = 32let baseScores→ [2, 4, 6] = [2, 4, 6]3var total→ 0 = 0total ← 5
pass 1 of 35for score2 in baseScores[2, 4, 6] {6 total→ 5 = total + score2 + bonus37}All 3 passes — pass 1 is the card above pass scoretotal1 2 0 → 5 2 4 5 → 12 3 6 12 → 21 print("bonus=\(bonus)")
9print("bonus=\(bonus3)")10print("total=\(total21)")outputbonus=3 total=21
Add Each Score
baseScoresstarts as[2, 4, 6].bonusis1.- The loop adds each score plus the bonus.
- The final total is
15. | Score | Added with bonus1| 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