Chapter 37: Swift Arrays: Loop
1. Why do we need different ways to loop?
When you have an array, you usually want to:
- Do something with each item
- Know the position (index) of each item
- Transform items into a new array
- Find something (first match, all matches…)
- Sum, count, filter, or reduce values
Swift gives you several very elegant ways to do this — and choosing the right one makes your code clearer, safer, and more efficient.
2. The 5 most important ways to loop over arrays
Way 1 – Simple for-in loop (most common & most readable)
|
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)") } |
When to use this:
- You only need the value (not the index)
- You are doing something simple like printing, logging, calling a function, updating UI…
Real-life example – show list of tasks
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let tasks = ["Buy groceries", "Finish report", "Call mom", "Gym"] print("Today's tasks:") for task in tasks { print("• \(task)") } |
Way 2 – for-in with index using enumerated()
This is the most common way when you need both the item and its position.
|
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 |
Real-life example – numbered list in console or debug log
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let logs = [ "User logged in", "API call failed", "Retry successful", "Session ended" ] print("Recent activity:") for (i, log) in logs.enumerated() { print(" [\(i + 1)] \(log)") } |
Way 3 – Loop over indices only (indices property)
Use this when you mainly need the positions and will access the array manually.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let scores = [85, 92, 78, 95, 88] for index in scores.indices { let score = scores[index] let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C" print("Student \(index + 1): \(grade)") } |
When to use this style:
- You need to modify the array while looping (carefully!)
- You are working with multiple arrays at the same index
- You want maximum control over iteration
Way 4 – forEach method (functional style)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let fruits = ["Mango", "Banana", "Apple"] fruits.forEach { fruit in print("→ I like \(fruit)") } // or shorter with implicit $0 fruits.forEach { print("→ I like \($0)") } |
Key differences from for-in:
- Cannot use break or continue
- Cannot return early from the function
- Looks more “functional” (good when chaining with map, filter…)
Realistic use case – small logging or side effects
|
0 1 2 3 4 5 6 7 8 9 10 |
let recentSearches = ["Swift arrays", "String interpolation", "forEach vs for-in"] recentSearches.forEach { query in print("User searched: \(query)") } |
Way 5 – Modern for try or for await (when dealing with throwing or async items)
These are advanced but very common in real apps today.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Example with throwing functions let urls = [ URL(string: "https://example.com/1")!, URL(string: "https://example.com/2")! ] for try await data in urls.asyncMap({ try await URLSession.shared.data(from: $0).0 }) { print("Downloaded data of size: \(data.count) bytes") } |
(We’ll cover async loops later — just showing it exists.)
6. Very Common Real-Life Examples
Example 1 – Display numbered list in console or debug
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let recentMessages = [ "Hey, how are you?", "Meeting at 3 PM", "Sent you the file", "Thanks!" ] print("Recent messages:") for (index, message) in recentMessages.enumerated() { print(" \(index + 1). \(message)") } |
Example 2 – Process items with position
|
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 |
let items = ["Phone", "Charger", "Case", "Screen guard"] var totalPrice: Double = 0 var receipt = "Receipt:\n" for (index, item) in items.enumerated() { let price: Double switch item { case "Phone": price = 74999 case "Charger": price = 1999 case "Case": price = 999 case "Screen guard": price = 499 default: price = 0 } totalPrice += price receipt += " \(index + 1). \(item) - ₹\(price)\n" } receipt += "-------------------\n" receipt += "Total: ₹\(totalPrice)" print(receipt) |
Example 3 – Filter & transform with forEach (functional style)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let temperatures = [28.5, 32.1, 35.8, 29.4, 31.2] temperatures.forEach { temp in let status = temp > 32 ? "Hot ☀️" : temp < 30 ? "Pleasant 🌤️" : "Warm 😅" print("\(temp)°C → \(status)") } |
7. Quick Summary – Which Loop Style to Choose
| Situation | Recommended 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 |
| Functional style, chaining, side effects | array.forEach { … } | Looks modern, good for small operations |
| Async / throwing items | for try await …, for await … | Modern concurrency code |
8. Small Practice – Try these now
- Create array of 5 favorite foods → Print them numbered using enumerated() → Print only items that contain “a” in the name
- Create array of numbers 1…10 → Print each number and whether it is even or odd → Use both for-in and forEach styles
- Create array of 4 task names → Print “Task 1: …” up to “Task 4: …” using index
Paste your code if you want feedback or improvements!
What would you like to explore next about arrays?
- Looping with filter, map, compactMap, reduce
- Sorting arrays (simple & custom sorting)
- Array slicing (prefix, suffix, dropFirst…)
- Safe index access & bounds checking
- Arrays in SwiftUI (List, ForEach, @State)
- Or move to another topic (dictionaries, sets, optionals…)
Just tell me — we’ll keep going in the same clear, detailed, teacher-like style 😊
