For in Swift
Swift provides several ways to write loops. Let’s explore the different types of loops and their usage.
When you run this program, you’ll see the following output:
Let’s break down the different types of loops in Swift:
While loop: This is the most basic type, with a single condition. It continues executing as long as the condition is true.
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.
Closed range loop: Using
...
creates a closed range that includes both the lower and upper bounds.Infinite loop with break: A
while true
loop will run indefinitely until youbreak
out of it orreturn
from the enclosing function.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.