In Swift, the for loop is a fundamental tool for iterating through collections, ranges, sequences, and arrays. It allows you to repeat a block of code a specific number of times or iterate over elements in a collection. The for
loop is widely used for tasks like processing data, performing calculations, or simply iterating over an array of values.
In this article, we’ll explore the for loop in Swift, how it works, and the different ways you can use it to iterate through ranges, arrays, and other collections. We’ll also look at variations of the for
loop and best practices for using it effectively in your Swift programs.
Basic Syntax of for
Loop
The most common use of a for
loop is iterating over a range of numbers. Here’s the basic syntax:
for variable in range {
// Code to execute
}
The loop runs through each value in the range
, and the code inside the loop is executed once for each value. The loop variable (variable
) takes on each value in the range sequentially.
Example 1: Iterating Over a Range
for i in 1...5 {
print("Iteration \(i)")
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
In this example, the for
loop iterates over the range 1...5
and prints the current value of i
for each iteration. The range operator ...
creates a closed range, meaning the loop includes both the start and end values.
Iterating Over Arrays
You can use a for
loop to iterate through an array and access each element one by one. This is particularly useful when you want to perform operations on each element in a collection.
Example 2: Iterating Over an Array
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print("I love \(fruit)!")
}
Output:
I love Apple!
I love Banana!
I love Cherry!
In this example, the for
loop iterates through each element in the fruits
array and prints a statement for each fruit.
Iterating Over Dictionaries
You can also iterate over a dictionary’s key-value pairs using a for
loop. Swift provides an easy way to access both the key and the value of each pair during iteration.
Example 3: Iterating Over a Dictionary
let studentGrades = ["Alice": 90, "Bob": 85, "Charlie": 92]
for (name, grade) in studentGrades {
print("\(name) scored \(grade) in the exam.")
}
Output:
Alice scored 90 in the exam.
Bob scored 85 in the exam.
Charlie scored 92 in the exam.
In this example, the for
loop iterates through the studentGrades
dictionary, extracting both the name
(key) and grade
(value) for each student.
Ranges in for
Loops
Swift offers several ways to define ranges for a for
loop. You can use closed ranges (...
), half-open ranges (..<
), or even stride to control the increment between each step of the loop.
Example 4: Half-Open Range
The half-open range operator (..<
) excludes the upper bound.
for i in 1..<5 {
print("Iteration \(i)")
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
In this example, the range 1..<5
includes values from 1
to 4
, but not 5
.
Example 5: Using stride
to Control Loop Steps
The stride(from:to:by:)
function allows you to specify a custom increment (step) for each iteration.
for i in stride(from: 0, to: 10, by: 2) {
print("Step \(i)")
}
Output:
Step 0
Step 2
Step 4
Step 6
Step 8
In this example, the for
loop increments by 2
each time, iterating through the numbers 0, 2, 4, 6, 8
.
Iterating with Index and Value
In some cases, you may need to access both the index and the value of elements in a collection. Swift provides a convenient method called enumerated()
that returns a tuple containing both the index and the value.
Example 6: Using enumerated()
with Arrays
let cities = ["New York", "London", "Tokyo"]
for (index, city) in cities.enumerated() {
print("City \(index + 1): \(city)")
}
Output:
City 1: New York
City 2: London
City 3: Tokyo
In this example, the enumerated()
method returns both the index and the value of each element in the cities
array, allowing you to print the city name alongside its position in the list.
Using where
Clause in for
Loops
You can use the where
clause in a for
loop to filter the elements you want to process. The where
clause adds a condition that must be true for the loop to process the current element.
Example 7: Using where
in a for
Loop
let numbers = [1, 2, 3, 4, 5, 6]
for number in numbers where number % 2 == 0 {
print("Even number: \(number)")
}
Output:
Even number: 2
Even number: 4
Even number: 6
In this example, the for
loop only processes numbers that are even (i.e., divisible by 2
).
Exiting a for
Loop Early
In Swift, you can use the break
statement to exit a for
loop early if a specific condition is met. This is useful when you only need to process up to a certain point and don’t want to continue iterating.
Example 8: Exiting a for
Loop Early with break
for i in 1...10 {
if i == 5 {
print("Stopping at \(i)")
break
}
print("Iteration \(i)")
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Stopping at 5
In this example, the for
loop exits when i
equals 5
due to the break
statement.
Skipping Iterations in a for
Loop
You can use the continue
statement to skip the current iteration of a for
loop and move to the next one. This is helpful when you want to skip certain elements based on a condition.
Example 9: Skipping Iterations with continue
for i in 1...5 {
if i == 3 {
continue // Skip iteration when i equals 3
}
print("Iteration \(i)")
}
Output:
Iteration 1
Iteration 2
Iteration 4
Iteration 5
In this example, the loop skips the iteration where i
equals 3
, thanks to the continue
statement.
Best Practices for Using for
Loops
- Use enumerated() for index-value access: When you need both the index and the value of elements, use
enumerated()
to avoid manual index tracking. - Avoid modifying collections while iterating: Modifying the collection you are iterating over can lead to unexpected behavior. Instead, create a copy of the collection if you need to make changes during iteration.
- Use
stride()
for custom increments: When you need to control the step value in a loop, use thestride()
function to specify custom increments. - Use
where
for filtering: Use thewhere
clause to filter elements directly within the loop, making your code cleaner and more concise.
Conclusion
The for loop in Swift is a versatile and powerful tool for iterating over collections, arrays, ranges, and sequences. Whether you need to process data, perform calculations, or simply loop through a series of values, the for
loop provides the flexibility you need. With additional tools like enumerated()
, stride()
, and the where
clause, Swift’s for
loop is both expressive and easy to use.
In this article, we covered:
- The basic syntax of a
for
loop. - Iterating over arrays, dictionaries, and ranges.
- Using
stride()
for custom increments andenumerated()
for index-value pairs. - Using the
where
clause to filter elements in a loop. - Exiting loops early with
break
and skipping iterations withcontinue
.
In the next article, we’ll explore while and repeat-while loops in Swift, how they differ from for
loops, and when to use them in your code.
Happy coding!