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.
Learn Swift on Mimo
Looping Through a Range
This loop prints numbers from 1 to 5, including both endpoints.
Swift
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.
Swift
for _ in 1...3 {
print("Hello!")
}
Looping Through an Array
You can iterate over an array to access each element in order.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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:.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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.
Swift
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
whereinside loops to filter values. - Prefer
forEachfor 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.
Looking to dive deeper into Swift for loops and other essential Swift concepts? Check out our Swift programming course.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot