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:

Swift

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

Swift

Output:

text

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):

Swift

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)

Swift

→ 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)

Swift

Key difference:

  • while → checks before → may run 0 times
  • repeat … while → checks afteralways runs at least once

4. Real-life examples — the situations where while is actually used

Example 1 – Retry network request (very common pattern)

Swift

Typical while retry pattern:

  • counter (attempt)
  • maximum tries
  • delay between attempts
  • break out early on success

Example 2 – Accumulate savings until goal

Swift

Example 3 – Wait for valid user input (command-line style)

Swift

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:

  1. Is there a variable that changes inside the loop?
  2. Does that variable move toward making the condition false?
  3. Is there a maximum number of iterations? (safety net)

Very good safety pattern (highly recommended):

Swift

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

  1. Countdown Start from 10, count down to 1 using while, then print “Blast off! 🚀”
  2. 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
  3. 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 😊

You may also like...

Leave a Reply

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