Chapter 54: While Loop
1. What does a while loop actually do?
A while loop keeps repeating a block of code as long as a certain condition remains true.
The English translation is:
While this condition is still true, please keep doing the code inside the curly braces. The moment the condition becomes false, stop repeating and continue after the loop.
Basic structure:
|
0 1 2 3 4 5 6 7 8 9 |
while conditionIsStillTrue { // code that gets repeated over and over // very important: something inside here must eventually make the condition false } |
The condition is checked before every execution of the body.
If the condition is already false when the loop starts → the body never runs (0 times).
2. The absolute first example – countdown
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var count = 5 print("Countdown starting...") while count > 0 { print(count) count -= 1 // ← THIS LINE IS CRITICAL } print("Blast off! 🚀") |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
Countdown starting... 5 4 3 2 1 Blast off! 🚀 |
The single most important thing to understand right now:
Every while loop must have a way to eventually make the condition false.
If you forget to change the variable that the condition depends on → infinite loop (the program hangs forever or crashes the device).
Infinite loop example (never do this):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
var count = 5 while count > 0 { print(count) // forgot count -= 1 → condition never becomes false // program will print 5 forever → infinite loop } |
3. The two kinds of while loops in Swift
Swift actually has two flavors of while loop:
3.1 while — check condition first (may run 0 times)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var money = 0 let ticketPrice = 500 while money < ticketPrice { print("You have ₹\(money) — need ₹\(ticketPrice)") money += 100 // pretend you earn 100 every round } print("You have enough! Buying ticket 🎟️") |
→ If you already had ₹1000 at the start → loop body never runs.
3.2 repeat … while — run at least once (check condition at the end)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var pin: String? repeat { print("Enter 4-digit PIN:") pin = readLine() if pin?.count != 4 { print("PIN must be exactly 4 digits. Try again.") } } while pin?.count != 4 print("PIN accepted: \(pin!)") |
Key difference:
- while → checks before → may run 0 times
- repeat … while → checks after → always runs at least once
4. Real-life examples — the situations where while is actually used
Example 1 – Retry network request (very common pattern)
|
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 |
func fetchUserProfile(maxRetries: Int = 3) -> String? { var attempt = 0 while attempt < maxRetries { attempt += 1 print("Trying to fetch profile... attempt \(attempt)/\(maxRetries)") // pretend network call let success = Bool.random() // 50% chance if success { return "Profile loaded successfully" } print("Failed. Waiting 2 seconds before retry...") Thread.sleep(forTimeInterval: 2.0) } print("Failed after \(maxRetries) attempts") return nil } let profile = fetchUserProfile() |
Typical while retry pattern:
- counter (attempt)
- maximum tries
- delay between attempts
- break out early on success
Example 2 – Accumulate savings until goal
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
let goal: Double = 100_000 var savings: Double = 0 var month = 0 while savings < goal { month += 1 let monthlyIncome = 45_000.0 let expenses = 32_000.0 + Double.random(in: -5_000...5_000) let savingsThisMonth = monthlyIncome - expenses savings += savingsThisMonth print("Month \(month): saved ₹\(String(format: "%.0f", savingsThisMonth)) → total: ₹\(String(format: "%.0f", savings))") } print("Goal reached after \(month) months!") |
Example 3 – Wait for valid user input (command-line style)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var answer: String = "" while answer.lowercased() != "yes" && answer.lowercased() != "no" { print("Do you want to continue? (yes/no)") if let input = readLine() { answer = input } else { print("Please type something.") } } if answer.lowercased() == "yes" { print("Continuing...") } else { print("Goodbye!") } |
5. Very Important Safety Rules – Prevent Infinite Loops
The #1 danger with while is the infinite loop.
Before you write any while, always ask yourself:
- Is there a variable that changes inside the loop?
- Does that variable move toward making the condition false?
- Is there a maximum number of iterations? (safety net)
Very good safety pattern (highly recommended):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var attempt = 0 let maxAttempts = 10 while someCondition && attempt < maxAttempts { attempt += 1 // try something if success { break // exit early on success } } if attempt >= maxAttempts { print("Operation failed after \(maxAttempts) attempts") } |
6. Very Common Beginner Mistakes & How to Avoid Them
| Mistake | Wrong code | Correct / Better habit | Why? |
|---|---|---|---|
| Forgetting to update the condition variable | while count > 0 { print(count) } | count -= 1 inside the loop | Infinite loop |
| Using while true without clear exit | while true { … } | Prefer repeat … while or clear break condition | Hard to see when it stops |
| Not handling empty / edge cases | while !array.isEmpty { … } without check | while let item = array.first { array.removeFirst() } | Prevents infinite loop on empty data |
| Deeply nested while + if | many nested loops | Extract to functions or flatten logic | Code becomes unreadable |
| Using while when for or forEach is clearer | var i = 0; while i < 10 { … i += 1 } | for i in 0..<10 { … } | for is usually safer & clearer |
7. Quick Reference – When to use while vs other loops
| Situation | Prefer while? | Prefer for-in / forEach? | Reason / guideline |
|---|---|---|---|
| You know the exact number of iterations | — | Yes | for i in 0..<count or for item in array |
| You don’t know how many times you’ll loop | Yes | — | Retry, wait for condition, accumulate until target |
| Need to loop at least once | Yes (repeat … while) | — | Guarantees first execution |
| Processing until collection is empty | Yes | — | while !array.isEmpty { … } |
| Waiting for user input / external event | Yes | — | while answer != “quit” { … } |
8. Small Practice – Try these right now
- Countdown Start from 10, count down to 1 using while, then print “Blast off! 🚀”
- Savings simulator Goal: ₹50,000 Start with ₹0 Each month add ₹4,500 + random bonus (–₹500 to +₹1,500) Print month number and current savings until goal is reached
- Password validator Ask user for password using repeat … while Keep asking until password is at least 8 characters long
Paste your code here if you want feedback, corrections or more elegant versions!
What would you like to explore next?
- repeat … while in more depth
- while let pattern (very common with optionals)
- How to safely avoid infinite loops
- while vs for vs forEach — decision guide
- Loops in SwiftUI (ForEach vs manual while)
- Or move to another topic (switch, functions, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
