Swift Loops

A loop runs the same block of code repeatedly. Think of it as a washing machine cycle — the same steps run again and again until the laundry is done. Swift provides three main loops: for-in, while, and repeat-while.

The for-in Loop

Use for-in when you know the number of times you want to repeat something.

Loop Over a Range

for i in 1...5 {
    print("Count: \(i)")
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

Loop Over an Array

let fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits {
    print(fruit)
}
// Output:
// Apple
// Banana
// Cherry

Ignoring the Loop Variable

Use an underscore when you need the repetition but not the index itself.

for _ in 1...3 {
    print("Swift is great!")
}
// Prints the message 3 times

The while Loop

A while loop keeps running as long as its condition is true. Use it when you do not know in advance how many iterations you need.

var countdown = 5

while countdown > 0 {
    print("T-minus \(countdown)")
    countdown -= 1
}
print("Liftoff!")

// Output:
// T-minus 5
// T-minus 4
// T-minus 3
// T-minus 2
// T-minus 1
// Liftoff!

Diagram: while Loop Flow

Start
  |
  v
Check condition
  |          \
true          false → Exit loop
  |
Execute body
  |
  +--→ Check condition again

The repeat-while Loop

A repeat-while loop runs the body first and checks the condition after. This guarantees the body executes at least once.

var attempts = 0

repeat {
    attempts += 1
    print("Attempt \(attempts)")
} while attempts < 3

// Output:
// Attempt 1
// Attempt 2
// Attempt 3

while vs repeat-while

Loop TypeChecks ConditionMinimum Runs
whileBefore the body0 (may never run)
repeat-whileAfter the body1 (always runs once)

Loop Control: break and continue

break — Exit the Loop Early

for number in 1...10 {
    if number == 6 {
        break
    }
    print(number)
}
// Output: 1 2 3 4 5  (stops at 6)

continue — Skip to the Next Iteration

for number in 1...10 {
    if number % 2 == 0 {
        continue
    }
    print(number)
}
// Output: 1 3 5 7 9  (skips even numbers)

Diagram: break vs continue

for i in 1...5

  i=1  → print 1
  i=2  → break  →→→ EXIT loop entirely
  i=3  (never reached)

for i in 1...5

  i=1  → print 1
  i=2  → continue →→ SKIP to i=3
  i=3  → print 3
  i=4  → continue →→ SKIP to i=5
  i=5  → print 5

Nested Loops

Loops can live inside other loops. The inner loop completes all its iterations for each single iteration of the outer loop.

for row in 1...3 {
    for col in 1...3 {
        print("\(row),\(col) ", terminator: "")
    }
    print()
}

// Output:
// 1,1  1,2  1,3
// 2,1  2,2  2,3
// 3,1  3,2  3,3

Labeled Loops

Labels let you break out of a specific outer loop from inside a nested loop.

outerLoop: for i in 1...3 {
    for j in 1...3 {
        if j == 2 {
            break outerLoop
        }
        print("i=\(i), j=\(j)")
    }
}
// Output: i=1, j=1  (breaks the outer loop when j hits 2)

stride — Custom Step Loops

Use stride to loop with a custom increment, including counting backwards.

for i in stride(from: 0, to: 10, by: 2) {
    print(i)
}
// Output: 0 2 4 6 8

for i in stride(from: 10, through: 0, by: -3) {
    print(i)
}
// Output: 10 7 4 1

Summary

Swift loops include for-in for known counts or collections, while for condition-based repetition, and repeat-while for guaranteed first execution. Use break to exit early and continue to skip iterations. Use labeled loops and stride for fine-grained control.

Leave a Comment

Your email address will not be published. Required fields are marked *