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)

Swift

Output:

text

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.

Swift

Output:

text

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)

Swift

3. Real-life examples — code you will actually write in apps

Example 1 – Numbered to-do list / task manager

Swift

Example 2 – Shopping cart receipt (very common in e-commerce)

Swift

Example 3 – Progress checklist / onboarding steps

Swift

Example 4 – Print a simple multiplication table

Swift

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

  1. Create array of 5 favorite movies → Print them numbered (1. Movie A, 2. Movie B…)
  2. Create array of numbers 1…10 → Print each number and whether it is even or odd → Use both simple for and enumerated() style
  3. 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 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *