Chapter 57: Swift For Loop
1. What is a for loop? (simple & honest explanation)
A for loop is used when you want to repeat the same piece of code a known number of times or once for each item in a collection.
In Swift, the for loop is extremely flexible and very safe compared to many other languages.
The most common feeling when you use for in Swift:
“For each thing in this list (or for each number in this range), do something.”
2. The three main forms of for you will use every day
Form 1 – Most common: for item in collection
This is the #1 most used loop in Swift.
|
0 1 2 3 4 5 6 7 8 9 10 |
let fruits = ["Mango", "Banana", "Apple", "Orange", "Guava"] for fruit in fruits { print("I like \(fruit)") } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
I like Mango I like Banana I like Apple I like Orange I like Guava |
When you use this style (almost always):
- You have an array, set, dictionary keys, string characters…
- You care about each element, but not about its position
- You are doing something simple: print, process, add to UI, send to server…
Form 2 – When you need the position → enumerated()
This is the second most common pattern — you use it whenever you want both the item and its index.
|
0 1 2 3 4 5 6 7 8 9 10 |
let fruits = ["Mango", "Banana", "Apple", "Orange"] for (index, fruit) in fruits.enumerated() { print("\(index + 1). \(fruit)") } |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
1. Mango 2. Banana 3. Apple 4. Orange |
Realistic use cases where you almost always use enumerated():
- Showing numbered lists (task list, search results, leaderboard)
- Creating numbered UI elements
- Logging with line numbers
- Pairing items with their position
Form 3 – Looping over a range of numbers (0..<count or 1…n)
|
0 1 2 3 4 5 6 7 8 9 |
// Classic 0-based index loop for i in 0..<5 { print("Round \(i + 1)") } |
|
0 1 2 3 4 5 6 7 8 9 |
// 1-based counting (very common in user-facing output) for level in 1...10 { print("Level \(level)") } |
|
0 1 2 3 4 5 6 7 8 9 10 |
// Count backwards for countdown in (1...5).reversed() { print("\(countdown)…") } print("Blast off! 🚀") |
4. Real-life examples — code you will actually write
Example 1 – Display numbered list of tasks / search results
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let tasks = [ "Finish Swift lesson", "Buy groceries", "Call mom", "Reply to emails", "Gym – 45 min" ] print("Today's tasks:") for (index, task) in tasks.enumerated() { print(" \(index + 1). \(task)") } |
Example 2 – Shopping cart / receipt (very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
struct CartItem { let name: String let price: Double let quantity: Int } let cart = [ CartItem(name: "Wireless Earbuds", price: 3499, quantity: 1), CartItem(name: "Phone Case", price: 799, quantity: 2), CartItem(name: "Screen Protector", price: 499, quantity: 1) ] print("Receipt") print("-----------------------------") var total: Double = 0 for (index, item) in cart.enumerated() { let lineTotal = item.price * Double(item.quantity) total += lineTotal print("\(index + 1). \(item.name) × \(item.quantity)") print(" ₹\(String(format: "%.2f", item.price)) each → ₹\(String(format: "%.2f", lineTotal))") } print("-----------------------------") print("Grand Total: ₹\(String(format: "%.2f", total))") |
Example 3 – Generate 1-based report lines
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let students = ["Rahul", "Priya", "Aarav", "Sneha"] let scores = [920, 980, 850, 950] print("Class Scoreboard") print("----------------") for (index, student) in students.enumerated() { let score = scores[index] let rank = index + 1 print("\(rank). \(student) – \(score) points") } |
Example 4 – Build numbered progress steps
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let steps = [ "Project setup", "Create data models", "Implement networking", "Build UI", "Add tests", "Deploy" ] print("Project Progress Checklist:") for (index, step) in steps.enumerated() { let status = index < 3 ? "✅ Done" : "⏳ Pending" print(" \(index + 1). \(step) – \(status)") } |
5. Very Common Beginner Mistakes & How to Avoid Them
| Mistake | Wrong / Dangerous code | Correct / Better habit | Why? |
|---|---|---|---|
| Using index without bounds check | for i in 0…10 { print(arr[i]) } | for i in 0..<arr.count { … } | Off-by-one → crash |
| Force-unwrapping first/last | fruits.first! | fruits.first ?? “None” or if let | Empty array → crash |
| Modifying array while iterating | for item in fruits { fruits.append(“…”) } | Build new array or use indices | Runtime error: collection mutated |
| Using for i in 1…array.count | for i in 1…fruits.count { … } | for i in 0..<fruits.count | Index 5 when count=5 → crash |
| Forgetting enumerated() when needing index | for fruit in fruits { print(“1. \(fruit)”) } | for (i, fruit) in fruits.enumerated() | Wrong numbering |
6. Quick Reference – Which for style to choose
| Situation | Recommended loop style | Why? / When to prefer it |
|---|---|---|
| Just process each item (no index needed) | for item in array { … } | Simplest & most readable |
| Need the position (index) | for (index, item) in array.enumerated() { … } | Most common when showing numbered lists |
| Only need indices (rare) | for index in array.indices { … } | When modifying or using multiple arrays |
| Need 1-based counting (UI/report) | for (index, item) in array.enumerated() { index + 1 } | Natural for humans |
| Know exact number of iterations | for i in 0..<10 { … } or for i in 1…10 { … } | Clear & safe |
7. Small Practice – Try these
- Create array of 5 favorite movies → Print them numbered (1. Movie A, 2. Movie B…)
- Create array of numbers 1…10 → Print each number and whether it is even or odd → Use both simple for and enumerated() style
- Create array of 6 task names → Print “Task 1: …” up to “Task 6: …” using index
Paste your code here if you want feedback or want to see cleaner versions!
What would you like to explore next?
- forEach, map, filter, reduce (functional style)
- Looping with indices and safe bounds checking
- Sorting arrays (simple & custom)
- Array slicing & ArraySlice lifetime
- Arrays in SwiftUI (List, ForEach, @State)
- Or move to another topic (dictionaries, sets, optionals…)
Just tell me — we’ll continue in the same clear, detailed, patient style 😊
