Activity 1
Accumulate a total
Loop through [12, 8, 15, 5] and calculate the total without using reduce.
Hint: Declare the running total with var before the loop.
Swift Fundamentals
Repeat work safely with for-in, ranges, while, and clear exit conditions.
Before you begin
Learning stage
Loops repeat a block of code. for-in is the usual choice when iterating over a sequence such as an array, range, dictionary, or string.
while repeats while a condition remains true. repeat-while performs its body once before checking the condition. break exits a loop and continue advances to its next iteration.
Learning stage
The loop enumerates lessons, skips locked items, and stops after the first incomplete available lesson.
let lessons = ["Types", "Control Flow", "Functions"]
let locked = Set(["Functions"])
for (index, lesson) in lessons.enumerated() {
if locked.contains(lesson) {
continue
}
print("\(index + 1). \(lesson)")
}
for number in 1...3 {
print("Attempt \(number)")
}Learning stage
These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.
Learning stage
Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.
Learning stage
Work through these activities in a small Xcode project. No embedded playground is required on this site.
Activity 1
Loop through [12, 8, 15, 5] and calculate the total without using reduce.
Hint: Declare the running total with var before the loop.
Activity 2
Print only positive numbers from a mixed array by using continue for zero and negative values.
Hint: Reject the values you don't want near the top of the loop.
Learning stage
Answer each question before revealing the explanation.
QUESTION 1
0..<3
The half-open range operator excludes its upper bound.
QUESTION 2
It skips the rest of the current iteration and proceeds with the next one.
Learning stage
Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.
Short answer: Use for-in when iterating over a known sequence; use while when repetition depends primarily on a changing condition.
for-in communicates bounded sequence traversal and manages iteration for you. while is appropriate when the number of iterations is not known in advance, but its exit condition must be designed carefully.
Possible follow-ups
Learning stage
Use the highest-level loop that expresses the work. Prefer direct sequence iteration, make boundaries explicit, and ensure condition-driven loops can terminate.