Collections
Collection Iteration
Loops can visit each value in a collection and build a result.
Accumulate values
collection_iteration.swift
let bonus =
let baseScores = [2, 4, 6]
var total = 0
for score in baseScores {
total = total + score + bonus
}
print("bonus=\(bonus)")
print("total=\(total)")
let bonus =
let baseScores = [2, 4, 6]
var total = 0
for score in baseScores {
total = total + score + bonus
}
print("bonus=\(bonus)")
print("total=\(total)")
let bonus =
let baseScores = [2, 4, 6]
var total = 0
for score in baseScores {
total = total + score + bonus
}
print("bonus=\(bonus)")
print("total=\(total)")
iteration
A `for` loop over an array handles each element in order. The running total shows how repeated updates build a final result.