← Back to Swift Course | Chapter 3: Control Flow | Lesson 5 of 8

while and repeat-while Loops

A while loop keeps repeating code as long as a condition stays true, and repeat-while does the same but always runs the code at least once first.

Basic while Loop

A while loop checks its condition before every iteration, so its body might not run at all if the condition starts false.

Example: Basic while Loop

markup
var countdown = 3
while countdown > 0 {
    print("T-minus \(countdown)")
    countdown -= 1
}
print("Liftoff!")

repeat-while Loop

A repeat-while loop checks its condition after running the body, guaranteeing the body executes at least once even if the condition is initially false.

Note: Compare this to a while loop with the same condition placed before the body -- repeat-while always runs once first.

Example: repeat-while Loop

markup
var attempts = 0
repeat {
    attempts += 1
    print("Attempt number \(attempts)")
} while attempts < 3
Common Mistakes
  1. Writing a while loop whose condition never becomes false, creating an infinite loop that hangs the program.
  2. Confusing repeat-while (Swift's version of do-while) with a regular while; repeat-while always executes the body at least once.
  3. Forgetting to update the loop's controlling variable inside the body, so the condition never changes.
Chapter Summary
  • while condition { } checks the condition before each iteration, possibly running zero times.
  • repeat { } while condition checks the condition after each iteration, always running at least once.
  • Both loops require the condition to eventually become false to avoid an infinite loop.
  • repeat-while is Swift's equivalent of do-while found in C-family languages.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.