For in Swift

Swift provides several ways to write loops. Let’s explore the different types of loops and their usage.

import Foundation

// The most basic type, with a single condition.
var i = 1
while i <= 3 {
    print(i)
    i += 1
}

// A classic initial/condition/after for loop.
for j in 0..<3 {
    print(j)
}

// Another way of accomplishing the basic "do this N times" iteration.
for i in 0...2 {
    print("range", i)
}

// A loop that continues until explicitly broken.
while true {
    print("loop")
    break
}

// You can also continue to the next iteration of the loop.
for n in 0..<6 {
    if n % 2 == 0 {
        continue
    }
    print(n)
}

When you run this program, you’ll see the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Let’s break down the different types of loops in Swift:

  1. While loop: This is the most basic type, with a single condition. It continues executing as long as the condition is true.

  2. For-in loop: This is used for iterating over a range, sequence, or collection. It’s similar to the classic C-style for loop but more concise and safer.

  3. Closed range loop: Using ... creates a closed range that includes both the lower and upper bounds.

  4. Infinite loop with break: A while true loop will run indefinitely until you break out of it or return from the enclosing function.

  5. Continue statement: You can use continue to skip the rest of the current iteration and move to the next one.

Swift’s for-in loop is versatile and can be used with ranges, arrays, dictionaries, and other sequences. The language doesn’t have a direct equivalent to Go’s for range over an integer, but using ranges (like 0..<3 or 0...2) achieves a similar result.

Note that Swift doesn’t have a C-style for loop (for i = 0; i < 10; i++). Instead, you would typically use a for-in loop with a range, or a while loop if you need more complex iteration logic.

We’ll see some other loop forms later when we look at collections, sequences, and other data structures.