Chapter 61: Swift For Loop (Real-Life)
1. Classic real pattern #1 – Display a numbered list (most frequent use)
This is by far the most common reason people use for + enumerated() in everyday code.
|
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 |
let recentOrders = [ "iPhone 16 Pro – ₹1,19,900", "AirPods Pro 2 – ₹24,900", "MagSafe Charger – ₹4,500", "Phone Case – ₹1,299", "Screen Protector – ₹799" ] print("Recent Orders (last 5)") print("──────────────────────") for (index, order) in recentOrders.enumerated() { let rank = index + 1 print(" #\(rank) \(order)") } // ── or even more polished (common in logs / receipts) for (index, order) in recentOrders.enumerated() { print(String(format: "%2d. %@", index + 1, order)) } |
Why this is so frequent:
- Almost every app shows lists with numbers: tasks, search results, cart items, notifications, leaderboard positions, order history, chat messages…
- Humans like 1-based numbering (1., 2., 3.), not 0-based
- enumerated() gives you both index and item for free
2. Real pattern #2 – Shopping cart / order receipt
This pattern appears in almost every e-commerce or food delivery app.
|
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 33 34 35 36 |
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), CartItem(name: "Charger Cable", price: 999, quantity: 1) ] print("Order Receipt") print("───────────────────────────────") var grandTotal: Double = 0 for (index, item) in cart.enumerated() { let lineTotal = item.price * Double(item.quantity) grandTotal += lineTotal let lineNumber = index + 1 print("\(lineNumber). \(item.name)") print(" ×\(item.quantity) @ ₹\(String(format: "%.2f", item.price))") print(" = ₹\(String(format: "%.2f", lineTotal))") print("───────────────────────────────") } print("Grand Total: ₹\(String(format: "%.2f", grandTotal))") print("Thank you for shopping! 🙏") |
Typical extensions in real apps:
- cart.remove(at: index) when user taps remove
- cart[index].quantity += 1 when user taps +
- cart.contains { $0.name == “…” } to avoid duplicate items
3. Real pattern #3 – Progress / checklist / onboarding steps
Very common in apps that guide the user (onboarding, setup wizard, project checklist).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let onboardingSteps = [ "Create your account", "Verify your email", "Upload profile picture", "Choose your interests", "Connect your contacts (optional)", "Start exploring the app!" ] print("Onboarding Progress") print("────────────────────") for (index, step) in onboardingSteps.enumerated() { let isDone = index < 3 // pretend first 3 steps are completed let mark = isDone ? "✅" : "⏳" print(" \(index + 1). \(step) \(mark)") } |
Real extension: In SwiftUI you would usually write:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
ForEach(Array(onboardingSteps.enumerated()), id: \.offset) { index, step in HStack { Text("\(index + 1). \(step)") Spacer() Image(systemName: index < 3 ? "checkmark.circle.fill" : "circle") .foregroundStyle(index < 3 ? .green : .gray) } } |
4. Real pattern #4 – Build a numbered report / log
Very common in console tools, debug logs, export features.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let activityLog = [ "User logged in", "Viewed product #4832", "Added to cart", "Applied coupon SAVE10", "Checkout started", "Payment successful" ] print("Activity Log – Last 6 actions") print("─────────────────────────────") for (index, action) in activityLog.enumerated() { let timestamp = "2025-07-15 14:3\(index+1):00" // pretend print("[\(timestamp)] #\(index + 1) \(action)") } |
5. Real pattern #5 – Simple numbered output without array
When you just need to repeat something N times with numbering.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let numberOfTickets = 8 print("Boarding Passes") print("───────────────") for ticketNumber in 1...numberOfTickets { print("Ticket #\(ticketNumber)") print(" Seat: \(["12A", "14B", "15C", "7D", "22E", "9F", "18G", "5H"][ticketNumber-1])") print(" Gate: B12") print(" Boarding: 15:40") print("───────────────") } |
6. 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…array.count { print(array[i]) } | for i in 0..<array.count { print(array[i]) } | 1…count tries to access index = count → crash |
| Force-unwrapping first/last | array.first! | array.first ?? “None” or if let first = array.first | Empty array → crash |
| Modifying array while iterating | for item in array { array.append(item) } | Build new array or use for index in array.indices | Runtime crash: collection mutated |
| Forgetting enumerated() when numbering | for item in array { print(“1. \(item)”) } | for (i, item) in array.enumerated() { print(“\(i+1). \(item)”) } | All items get numbered “1.” |
| Using for i in 0…array.count | for i in 0…array.count { … } | for i in 0..<array.count | Crash on last index |
7. Quick Summary – 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 position / 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 |
| Repeat exact number of times | for i in 0..<n { … } or for i in 1…n { … } | Clear & safe |
| Want 1-based numbering in output | for (index, item) in array.enumerated() { index + 1 } | Natural for humans |
8. Small Practice – Try these right now
- Create array of 6 favorite songs → Print them numbered (1. Song A, 2. Song B…)
- Create array of 8 numbers (any) → Print each number with its position and whether it is even or odd → Use enumerated()
- Create array of 5 tasks → Print “Task #1: …”, “Task #2: …” using index
Paste your code here if you want feedback, corrections or more polished versions!
What would you like to explore next?
- forEach, map, filter, reduce (functional style)
- Looping with indices and safe bounds checking
- Nested for loops (2D grids, tables, patterns)
- Sorting arrays (simple & custom)
- Arrays in SwiftUI (List, ForEach, @State)
- Or move to another topic (dictionaries, sets, optionals, switch…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
