The for-in Loop
for item in collection {
// use item
}
for i in 1...5 { } // closed range
for i in 0..<count { } // half-open range
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
// Loop over `1...5`, binding each item to `i`
for i in 1...5 {
// Print "Count: \(i)" to the console
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
// Declare a constant `fruits`, set to `["apple", "banana", "cherry"]`
let fruits = ["apple", "banana", "cherry"]
// Loop over `fruits`, binding each item to `fruit`
for fruit in fruits {
// Print "Fruit: \(fruit)" to the console
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.
0..<numbers.count is the idiomatic way to loop over valid indices without going out of bounds.Example: Half-Open vs Closed Ranges
// Declare a constant `numbers`, set to `[10, 20, 30]`
let numbers = [10, 20, 30]
// Loop over `0..<numbers.count`, binding each item to `index`
for index in 0..<numbers.count {
// Print "Index \(index): \(numbers[index])" to the console
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: