Repeat work with for-in
Repeat work with for-in
A teacher wants to total several scores. A for-in loop visits each element of a sequence and performs the body for that element. It lets you describe one calculation without duplicating it for every student.
The loop variable receives the next element on each iteration. A running total stores state across iterations. Ranges such as 1...3 include their upper bound, while 0..<3 exclude it. Nested loops perform the inner sequence for each outer iteration, so their total work can multiply.
What you’ll learn
- Trace a running total across each iteration.
- Distinguish break, continue and nested repetition.
Repeat work with for-in in the example
Total 0
A teacher wants to total several scores.
Total 0Add each score
The loop variable receives the next element on each iteration.
Add each scoreTotal 240
Total starts at zero, becomes 70, then 150, then 240.
Total 240
Work through repeat work with for-in
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
let scores = [70, 80, 90]
var total = 0
for score in scores {
total += score
}
print(total)Expected output
240Follow the execution
Total starts at zero, becomes 70, then 150, then 240. The print lies outside the loop, so it displays the finished total once. Moving it inside would display intermediate totals instead.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Repeat work with for-in
Your task: What total results if you append another score of 60?
Swift · complete program
let scores = [70, 80, 90]
var total = 0
for score in scores {
total += score
}
print(total)Worked answer
The total becomes 300 because a fourth iteration adds 60 to 240. The loop body needs no extra copy; it follows the collection’s elements.
Understand break and continue
Use break to leave the loop and continue to skip the rest of one iteration. Neither means “skip the entire program.” Do not mutate a collection’s iteration structure casually; create a deliberate transformation or a separate result when changing its contents.
Check your decision
Repeat work with for-in in practice
The total becomes 300 because a fourth iteration adds 60 to 240. The loop body needs no extra copy; it follows the collection’s elements. Use break to leave the loop and continue to skip the rest of one iteration.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.