Chapter 58: For Loop
1. Why do we need a for loop?
A for loop is the most natural way to say:
“Please do this same thing once for every item in this list / collection / range.”
In everyday language:
- “For each fruit in my basket, print its name.”
- “For every number from 1 to 10, add it to the total.”
- “For each row in the table, show the student’s name and score.”
Swift’s for loop is very expressive and very safe compared to older languages — you almost never need to manually manage an index counter.
2. The three most common forms of for (you will use these 95% of the time)
Form A – for item in collection (the most frequent style)
|
0 1 2 3 4 5 6 7 8 9 10 |
let fruits = ["Mango", "Banana", "Apple", "Orange", "Guava", "Pineapple"] for fruit in fruits { print("I love eating \(fruit) 🍋") } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
I love eating Mango 🍋 I love eating Banana 🍋 I love eating Apple 🍋 I love eating Orange 🍋 I love eating Guava 🍋 I love eating Pineapple 🍋 |
When you use this style (almost always at first):
- You only care about each element (the value)
- You don’t need to know its position in the list
- You are doing something simple: print, process, add to another list, show in UI…
Form B – for (index, item) in collection.enumerated() (when you need the position)
This is the second most common form — you use it as soon as you need numbering or positioning.
|
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). I love \(fruit)") } |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
1. I love Mango 2. I love Banana 3. I love Apple 4. I love Orange |
Typical real situations where you almost always use enumerated():
- Showing numbered lists (tasks, search results, leaderboard, cart items)
- Creating numbered UI rows / cells
- Logging with line numbers
- Pairing items with their position in reports
Form C – for number in range (when you want to count / repeat N times)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// 0-based (most common for indices) for i in 0..<5 { print("Round \(i + 1)") } // 1-based (very common in user messages / reports) for level in 1...10 { print("Level \(level) unlocked!") } // Backwards for countdown in (1...5).reversed() { print("\(countdown)…") } print("Blast off! 🚀") |
3. Real-life examples — code you will actually write in apps
Example 1 – Numbered to-do list / task manager
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let tasks = [ "Finish Swift lesson on loops", "Buy vegetables & milk", "Call mom", "Reply to pending emails", "Gym – 45 min cardio" ] print("Today's To-Do List") print("-------------------") for (index, task) in tasks.enumerated() { let status = index < 2 ? "✅ Done" : "⏳ Pending" print(" \(index + 1). \(task) \(status)") } |
Example 2 – Shopping cart receipt (very common in e-commerce)
|
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 – Progress checklist / onboarding steps
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
let onboardingSteps = [ "Create account", "Verify email", "Set up profile picture", "Choose interests", "Connect contacts (optional)", "Start exploring!" ] print("Onboarding Progress") print("-------------------") for (index, step) in onboardingSteps.enumerated() { let isCompleted = index < 3 // pretend first 3 are done let mark = isCompleted ? "✅" : "⏳" print(" \(index + 1). \(step) \(mark)") } |
Example 4 – Print a simple multiplication table
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let number = 7 print("\(number) × Table") print("------------") for i in 1...10 { let result = number * i print(" \(number) × \(i) = \(result)") } |
4. Very Common Beginner Mistakes & How to Avoid Them
| Mistake | Wrong / Dangerous code | Correct / Better habit | Why? |
|---|---|---|---|
| Using 1…count instead of 0..<count | for i in 1…fruits.count { … } | for i in 0..<fruits.count { … } | Index 5 when count=5 → crash |
| Force-unwrapping first / last | fruits.first! | fruits.first ?? “None” or if let first = fruits.first | Empty array → crash |
| Modifying array while iterating | for fruit in fruits { fruits.append(“…”) } | Build new array or use indices / forEach | Runtime error: collection mutated |
| Forgetting enumerated() when needing index | for fruit in fruits { print(“1. \(fruit)”) } | for (i, fruit) in fruits.enumerated() { print(“\(i+1). \(fruit)”) } | Wrong numbering |
| Using for i in 0…array.count | for i in 0…array.count { … } | for i in 0..<array.count | 0…count tries to access index count → crash |
5. Quick Reference – Which for style to choose
| You want to do… | Recommended style | Why / When to prefer it |
|---|---|---|
| Just process each item (no position needed) | for item in array { … } | Simplest & most readable |
| Need the position / want numbering | 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 parallel arrays |
| Want 1-based numbering (user-facing) | for (index, item) in array.enumerated() { index + 1 } | Natural for humans |
| Repeat exact number of times | for i in 0..<10 { … } or for i in 1…10 { … } | Clear & safe |
6. Small Practice – Try these right now
- 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, patient, detailed style 😊
