Swift Loops
A loop repeats a block of code multiple times. Instead of writing the same code ten times, you write it once and tell the loop how many times to run it. Loops save time and eliminate repetition.
The Printing Press Analogy
┌───────────────────────────────────────────────┐
│ Without Loop vs With Loop │
│ │
│ Without: With loop: │
│ print("Page 1") for i in 1...100 { │
│ print("Page 2") print("Page \(i)")│
│ print("Page 3") } │
│ ... (100 lines) │
│ │
│ A loop is like a printing press — │
│ one setup, runs hundreds of times. │
└───────────────────────────────────────────────┘
for-in Loop – Repeat a Set Number of Times
for i in 1...5 {
print("Count: \(i)")
}
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
The for-in loop runs once for each value in the range. Here it runs five times, and each time i holds the current count.
Skipping the Counter Variable
for _ in 1...3 {
print("Hello!")
}
// Hello!
// Hello!
// Hello!
When you do not need the loop counter, replace it with _. Swift ignores the count and just repeats the block.
Looping Over an Array
let fruits = ["Apple", "Mango", "Banana"]
for fruit in fruits {
print("I like \(fruit)")
}
// I like Apple
// I like Mango
// I like Banana
A for-in loop moves through each item in a list. The variable fruit holds one item per cycle.
while Loop – Repeat Until a Condition is False
var countdown = 5
while countdown > 0 {
print("\(countdown)...")
countdown -= 1
}
print("Liftoff!")
// 5... 4... 3... 2... 1... Liftoff!
A while loop checks its condition before each run. Once countdown reaches 0, the condition becomes false and the loop stops.
repeat-while Loop – Run at Least Once
var number = 10
repeat {
print("Number is \(number)")
number += 1
} while number < 10
// Number is 10
A repeat-while loop runs the block first, then checks the condition. Even though number is already 10 and the condition fails immediately, the block runs once.
for vs while vs repeat-while
┌──────────────────────────────────────────────────────┐
│ for-in → Use when you know how many times │
│ while → Use when you don't know, check first │
│ repeat-while → Use when you must run at least once │
└──────────────────────────────────────────────────────┘
break – Exit the Loop Early
for i in 1...10 {
if i == 5 {
break
}
print(i)
}
// 1 2 3 4
break stops the loop immediately. As soon as i equals 5, the loop ends before printing 5.
continue – Skip One Cycle
for i in 1...6 {
if i % 2 == 0 {
continue
}
print(i)
}
// 1 3 5
continue skips the rest of the current cycle and jumps to the next one. Even numbers trigger continue, so only odd numbers print.
Nested Loops
for row in 1...3 {
for col in 1...3 {
print("\(row),\(col)", terminator: " ")
}
print("")
}
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3
Nested loops are useful for working with grids, tables, or any two-dimensional data. The inner loop completes fully for every single step of the outer loop.
