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:

Swift

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

Swift

Output:

text

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

Swift

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
Swift

Output:

text

Even if number started > 5, the body would run once.

Realistic use case for repeat … while:

Swift

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

Swift

Typical while retry pattern:

  • counter (attempt)
  • maximum attempts
  • delay between tries
  • collect last error for reporting

Example 2 – Accumulate until target reached

Swift

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

Swift

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:

  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 counter)?

Safety counter pattern (very good habit):

Swift

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

  1. Write a countdown from 10 to 1 using while, then print “Blast off! 🚀”
  2. 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
  3. 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 😊

You may also like...

Leave a Reply

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