The for-in Loop
Iterating Over a Range
A for-in loop can iterate over a numeric range, running the body once for each value in that range.
Example: Iterating Over a Range
for i in 1...5 {
print("Count: \(i)")
}
Login to try C/C++/Java/PHP code in the editor
Iterating Over an Array
The same for-in syntax works directly over an array, giving you each element in order.
Example: Iterating Over an Array
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print("Fruit: \(fruit)")
}
Login to try C/C++/Java/PHP code in the editor
Half-Open vs Closed Ranges
..< creates a half-open range that excludes its upper bound, while ... creates a closed range that includes it -- an important distinction when looping over array indices.
Note: 0..<numbers.count is the idiomatic way to loop over valid indices without going out of bounds.
Example: Half-Open vs Closed Ranges
let numbers = [10, 20, 30]
for index in 0..<numbers.count {
print("Index \(index): \(numbers[index])")
}
Login to try C/C++/Java/PHP code in the editor
- Using a C-style
for i = 0; i < n; i++loop; that syntax was removed from Swift entirely -- usefor i in 0..<ninstead. - Confusing the closed range
...(includes both ends) with the half-open range..<(excludes the upper end). - Trying to modify the loop variable inside the loop body expecting it to affect iteration; the loop variable is a fresh constant each iteration.
for item in collectioniterates over every element of an array, range, dictionary, or other sequence.0..<5is a half-open range excluding 5;0...5is closed and includes 5.- The loop variable is a constant by default, freshly bound each iteration.
- for-in works on arrays, ranges, strings, dictionaries, and any type conforming to
Sequence.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: