for-in Loops and Ranges
Prerequisites: Operators
A loop repeats code. A for-in loop runs once for each item in a
sequence — a range of numbers, the elements of an array, or the
characters of a string.
Looping over a range
for i in 1...3 {
print("Pass \(i)")
}
Pass 1
Pass 2
Pass 3
1...3 includes 3; 0..<3 would give 0, 1, 2 — the natural choice when
counting positions, which start at 0.
Looping over a collection
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print("I like \(fruit)")
}
I like apple
I like banana
I like cherry
enumerated() also gives each position:
let fruits = ["apple", "banana"]
for (index, fruit) in fruits.enumerated() {
print("\(index + 1). \(fruit)")
}
1. apple
2. banana
Steps and reverse order
for n in stride(from: 0, through: 10, by: 5) {
print(n, terminator: " ")
}
print()
for n in (1...3).reversed() {
print(n, terminator: " ")
}
print()
0 5 10
3 2 1
stride(from:to:by:) excludes the end; stride(from:through:by:)
includes it.
When you don't need the value
Use _ if the loop variable isn't used:
for _ in 1...3 {
print("Hip hip hooray!")
}
Common mistakes
- Writing
1..3— that's not Swift syntax. Use1...3or1..<3. - Creating a range where the start is bigger than the end, like
5...1. It crashes at runtime; use(1...5).reversed().
Practice
Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50.
Show solution
for n in 1...10 {
print("5 x \(n) = \(5 * n)")
}