Lesson 15Control Flow
For-In Loops
Repeating Code with Loops
The for-in loop lets you repeat code for each item in a collection or range!
Range Types
1...5Closed range: 1, 2, 3, 4, 5
Includes both endpoints
1..<5Half-open: 1, 2, 3, 4
Excludes upper bound
What You Can Loop Through
🔢
Ranges
1...10📦
Arrays
[1, 2, 3]📝
Strings
"Hello"Stride Function
Use stride() for custom step sizes:
stride(from: 0, to: 10, by: 2)→ 0, 2, 4, 6, 8stride(from: 10, through: 0, by: -2)→ 10, 8, 6, 4, 2, 0
Tips & Tricks
- Use
_if you don't need the loop variable - Use
.enumerated()to get both index and value - Arrays use 0-based indexing!
main.swift
// Loop through a range (1 to 5)
for i in 1...5 {
print("Count: \(i)")
}
// Output: 1, 2, 3, 4, 5
// Loop excluding last number (1 to 4)
for i in 1..<5 {
print("Number: \(i)")
}
// Output: 1, 2, 3, 4
// Loop through an array
let fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits {
print("I like \(fruit)")
}
// Loop with index using enumerated()
for (index, fruit) in fruits.enumerated() {
print("\(index + 1). \(fruit)")
}
// Loop through a string
for char in "Swift" {
print(char)
}
// Output: S, w, i, f, t
// Loop through dictionary
let scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
for (name, score) in scores {
print("\(name): \(score) points")
}
// Stride - custom step
for i in stride(from: 0, to: 10, by: 2) {
print("Even: \(i)")
}
// Output: 0, 2, 4, 6, 8
// Countdown using stride
for i in stride(from: 5, through: 1, by: -1) {
print("\(i)...")
}
print("Blast off!")
// Ignoring the loop variable
for _ in 1...3 {
print("Hello!")
}Try It Yourself!
Create a loop that prints the multiplication table for a number (1-10)!