Chapter 53: Swift While Loop
1. What does a while loop actually do?
A while loop keeps repeating a block of code as long as a condition remains true.
The most important sentence to remember:
While the condition is true, execute the body. As soon as the condition becomes false, stop (and continue after the loop).
Basic structure:
|
0 1 2 3 4 5 6 7 8 |
while condition { // code that runs repeatedly — as long as condition is true } |
The condition is checked before every execution of the body.
If the condition is false from the very beginning → the loop body never runs (0 times).
2. Very first examples – feel the rhythm
Example 1 – Countdown
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var count = 5 while count > 0 { print("\(count)…") count -= 1 // very important! decrease the counter } print("Lift off! 🚀") |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
5… 4… 3… 2… 1… Lift off! 🚀 |
Critical point: If you forget to change the condition inside the loop → infinite loop (program hangs / crashes device)
Wrong example (infinite loop – never do this):
|
0 1 2 3 4 5 6 7 8 9 10 11 |
var count = 5 while count > 0 { print(count) // forgot count -= 1 → loop never ends } |
3. repeat … while — the other flavor (check condition at the end)
There is a second kind of while loop in Swift: repeat … while
Difference:
- while → checks condition before running the body (may run 0 times)
- repeat … while → runs the body at least once, checks condition after
|
0 1 2 3 4 5 6 7 8 9 10 11 |
var number = 1 repeat { print(number) number += 1 } while number <= 5 |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 |
Even if number started > 5, the body would run once.
Realistic use case for repeat … while:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var input: String? repeat { print("Enter your name (minimum 3 characters):") input = readLine() } while input == nil || input!.count < 3 print("Hello, \(input!)!") |
→ Guarantees that the user is asked at least once.
4. Real-life examples — code you will actually write
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 29 30 31 32 33 34 35 |
func fetchUserData(maxRetries: Int = 3) -> String? { var attempt = 0 var lastError: Error? while attempt < maxRetries { attempt += 1 print("Attempt \(attempt)/\(maxRetries)…") do { // pretend network call let success = Bool.random() // 50% chance of success if success { return "User data received" } else { throw NSError(domain: "Network", code: -1009) } } catch { lastError = error print("Failed: \(error.localizedDescription)") // wait a bit before retry Thread.sleep(forTimeInterval: 1.0) } } print("All attempts failed") return nil } let result = fetchUserData() |
Typical while retry pattern:
- counter (attempt)
- maximum attempts
- delay between tries
- collect last error for reporting
Example 2 – Accumulate until target reached
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let targetSavings: Double = 50000 var currentSavings: Double = 0 var month = 0 while currentSavings < targetSavings { month += 1 let monthlyDeposit = 4500.0 + Double.random(in: -500...1500) // simulate variation currentSavings += monthlyDeposit print("Month \(month): saved ₹\(String(format: "%.0f", monthlyDeposit)) → total ₹\(String(format: "%.0f", currentSavings))") } print("Goal reached after \(month) months!") |
Example 3 – Wait for user input (command-line tools)
|
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 != "yes" && answer != "no" { print("Do you want to continue? (yes/no)") answer = readLine()?.lowercased() if answer == nil { print("Please type something.") } } if answer == "yes" { print("Continuing...") } else { print("Goodbye!") } |
5. Very Important Safety Rule – Prevent Infinite Loops
The #1 danger with while is the infinite loop.
Every while must have at least one path that makes the condition eventually false.
Checklist before writing any while:
- 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 counter)?
Safety counter pattern (very good habit):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var attempt = 0 let maxAttempts = 10 while someCondition && attempt < maxAttempts { attempt += 1 // try something } if attempt >= maxAttempts { print("Gave up after \(maxAttempts) attempts") } |
6. Very Common Beginner Mistakes & Fixes
| Mistake | Wrong code | Correct / Better habit | Why? |
|---|---|---|---|
| Forgetting to change the condition | while count > 0 { print(count) } | count -= 1 inside loop | Infinite loop |
| Using while true without break | while true { … } | Prefer repeat or add clear break condition | Hard to see exit condition |
| Not handling empty / edge cases | while array.count > 0 { … } without check | while let item = array.first { … } or guard | May crash or loop forever on empty data |
| Deeply nested while + if | many nested loops | Try to flatten or extract functions | Hard to read & debug |
| Using while when for would be clearer | var i = 0; while i < 10 { … i += 1 } | for i in 0..<10 { … } | for is usually clearer & safer |
7. Quick Reference – When to choose while vs for
| Situation | Prefer while? | Prefer for-in? | 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 need | Yes | — | Retry, wait for condition, accumulate until target |
| Need to loop at least once | Yes (repeat) | — | repeat … while guarantees first run |
| Processing until collection is empty | Yes | — | while !array.isEmpty { … } |
| Waiting for user input / external event | Yes | — | while answer != “quit” { … } |
8. Small Practice – Try these
- Write a countdown from 10 to 1 using while, then print “Blast off! 🚀”
- Simulate saving money: start with ₹0, goal ₹50 000 every month add ₹4 500 + random bonus (-500…+1500) print month number and current savings until goal reached
- Ask user for password until it’s at least 8 characters long (use repeat … while)
Paste your code here if you want feedback or want to see cleaner versions!
What would you like to explore next?
- repeat … while in more depth
- while let pattern (very common with optionals)
- Infinite loops — how to debug & prevent them
- 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 😊
