SWIFT
Swift For Loop: Syntax, Usage, and Examples
A for loop in Swift repeats a block of code for a fixed number of iterations. It is commonly used for iterating over arrays, dictionaries, and ranges.
How to Use For Loops in Swift
Swift provides different types of for loops, each with its own syntax.
Looping Through a Range
This loop prints numbers from 1 to 5, including both endpoints.
for number in 1...5 {
print(number)
}
If you don’t need the loop variable, use an underscore _
to ignore it. The loop below prints "Hello!" three times.
for _ in 1...3 {
print("Hello!")
}
Looping Through an Array
You can iterate over an array to access each element in order.
let names = ["Alice", "Bob", "Charlie"]
for name in names {
print(name)
}
Looping Through a Dictionary
To iterate through a dictionary, use a for loop with key-value pairs.
let scores = ["Alice": 90, "Bob": 85, "Charlie": 88]
for (name, score) in scores {
print("\(name) scored \(score) points.")
}
When to Use For Loops in Swift
You should use for loops when you know the number of iterations in advance.
Processing an Array
A for loop helps process each element of an array, such as doubling each number.
let numbers = [2, 4, 6, 8]
for num in numbers {
print(num * 2) // Output: 4, 8, 12, 16
}
Using an Index
The enumerated()
method provides both an index and a value while looping through an array.
let fruits = ["Apple", "Banana", "Cherry"]
for (index, fruit) in fruits.enumerated() {
print("\(index): \(fruit)")
}
Iterating in Reverse
The reversed()
method allows you to loop over an array in reverse order.
let letters = ["A", "B", "C"]
for letter in letters.reversed() {
print(letter) // Output: C, B, A
}
Examples of For Loops in Swift
Looping with a Stride
The stride(from:to:by:)
function lets you skip values while looping.
for number in stride(from: 0, to: 10, by: 2) {
print(number) // Output: 0, 2, 4, 6, 8
}
If you want to include the upper bound, use through:
instead of to:
.
for number in stride(from: 0, through: 10, by: 2) {
print(number) // Output: 0, 2, 4, 6, 8, 10
}
Filtering Items in a Loop
Using the where
clause inside a for loop allows you to filter values.
let scores = [50, 75, 90, 65, 100]
for score in scores where score >= 80 {
print("High score: \(score)")
}
Nested For Loops
A nested for loop runs inside another for loop, creating multiple iterations.
for row in 1...3 {
for column in 1...3 {
print("Row \(row), Column \(column)")
}
}
Breaking Out of a Loop
Use break
to stop the loop early. This loop prints numbers until it reaches 5.
for number in 1...10 {
if number == 5 {
break // Stops the loop at 5
}
print(number)
}
Skipping Iterations
Use continue
to skip specific iterations without stopping the loop. This loop skips the number 3.
for number in 1...5 {
if number == 3 {
continue // Skips 3
}
print(number)
}
Learn More About For Loops in Swift
Swift offers several ways to refine for loops.
Using For Loops with Sets
Since sets don’t have a fixed order, looping over them may produce results in any order.
let uniqueNumbers: Set = [10, 20, 30]
for num in uniqueNumbers {
print(num)
}
Using For Loops with Tuples
You can iterate over an array of tuples to access multiple values at once.
let users = [("Alice", 25), ("Bob", 30), ("Charlie", 28)]
for (name, age) in users {
print("\(name) is \(age) years old.")
}
For Loops vs. While Loops
A for loop is best when the number of iterations is known ahead of time. If the loop depends on a condition instead of a fixed count, use a while loop instead.
var count = 5
while count > 0 {
print(count)
count -= 1
}
For Loop with Optionals
If you’re looping through an array of optionals, use case let
to safely unwrap values.
let optionalNumbers: [Int?] = [1, nil, 3, nil, 5]
for case let number? in optionalNumbers {
print(number)
}
Using Labeled Breaks
Swift allows labeled loops to break out of specific loops when using nested loops.
outerLoop: for i in 1...3 {
for j in 1...3 {
if i == 2 && j == 2 {
break outerLoop // Breaks out of both loops
}
print("\(i), \(j)")
}
}
Best Practices for Using For Loops in Swift
- Use
enumerated()
when you need an index. - Use
stride(from:to:by:)
when skipping values. - Use
where
inside loops to filter values. - Prefer
forEach
for simpler iteration without control flow modifications.
The for loop in Swift is a powerful tool for iterating over ranges, collections, and sequences. You can modify it using stride, filtering, or optional binding to make your code more efficient.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.