Chapter 56: Real-Life Examples

1. Retry a failing operation (most classic real-life use of while)

Network calls, file operations, payment gateways, Bluetooth connections, etc. — they fail sometimes. A very common pattern is: try again a few times before giving up.

Swift

Why while here?

  • We don’t know in advance how many attempts we’ll need (could succeed on 1st, or fail all)
  • We have a clear exit condition (attempts reach limit)
  • We want to control the delay and logging between attempts

Safety improvement (very common in production code):

Swift

2. Keep asking user for valid input (command-line tools, setup wizards)

Swift

Why while true + break here?

  • We must keep asking until valid input → no “maximum tries”
  • while true + break is very readable for “keep going until I say stop”
  • continue skips to next iteration when input is bad

3. Accumulate / collect until goal is reached

Swift

Why while here?

  • We don’t know how many months it will take
  • We have a clear stopping condition (savings ≥ goal)
  • We added a safety counter (max 120 months) — very good habit

4. Process items until list is empty

Swift

Alternative (often cleaner – many developers prefer this):

Swift

5. Very Common Beginner Mistakes & How to Fix Them

Mistake Wrong / Dangerous code Correct / Better habit Why?
Forgetting to update the condition variable while count > 0 { print(count) } count -= 1 inside loop Infinite loop
Using while true without safe exit while true { … } while true { if done { break } } or counter Hard to see when it stops
Not handling empty collection while array.count > 0 { array[0]… } while let item = array.first { array.removeFirst() } Prevents crash / infinite loop
Modifying collection while looping over it for item in array { array.append(item) } Use while + removeFirst() or indices Runtime error: collection mutated
No safety limit while !success { tryAgain() } var attempt = 0; while … && attempt < 10 { … } Prevents infinite loop in case of bug

6. Quick Summary – When to reach for while

Situation Use while or repeat … while? Alternative (when to prefer) Typical pattern
Retry until success (network, payment, input) Yes for try? in some async cases while attempt < max { try… }
Keep asking user until valid input Yes (repeat … while) while + optional binding repeat { readLine() } while invalid
Accumulate until goal / threshold Yes for if fixed steps while savings < goal { savings += monthly }
Process collection until empty Yes for item in array { … } if not modifying while !array.isEmpty { array.removeFirst() }
You know exact number of iterations for i in 0..<count { … } for is clearer & safer

7. Small Practice – Try these now

  1. Countdown Start from 10, count down to 1 with while, then print “Lift off! 🚀”
  2. Savings until goal Goal: ₹50,000 Start with ₹0 Each month add ₹4,500 + random bonus (–₹500 to +₹1,500) Print month and current savings until goal is reached
  3. PIN entry Use repeat … while to keep asking for a 4-digit PIN until user enters exactly 4 digits (0-9)

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)
  • Infinite loops — how to debug & prevent them safely
  • 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 😊

You may also like...

Leave a Reply

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