For loops are a fundamental control flow construct in Swift, enabling efficient iteration over collections and ranges. They provide a concise way to execute a block of code repeatedly.
The basic syntax of a for loop in Swift is as follows:
for item in collection {
// Code to be executed for each item
}
Here, item
represents each element in the collection
as the loop iterates.
One common use of for loops is to iterate over arrays:
let fruits = ["apple", "banana", "orange"]
for fruit in fruits {
print("I like \(fruit)")
}
This loop will print each fruit in the array.
Swift for loops can also iterate over ranges:
for number in 1...5 {
print(number)
}
This loop prints numbers from 1 to 5, inclusive.
For more complex iterations, use the stride(from:to:by:)
function:
for i in stride(from: 0, to: 10, by: 2) {
print(i)
}
This loop prints even numbers from 0 to 8.
You can add a where clause to filter iterations:
for number in 1...10 where number % 2 == 0 {
print(number)
}
This loop only prints even numbers between 1 and 10.
To access both the index and value of a collection, use enumerated()
:
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
print("Color \(index + 1): \(color)")
}
To further enhance your Swift programming skills, explore these related topics:
By mastering for loops, you'll gain a powerful tool for efficient data processing and control flow in your Swift applications.