← 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.
Syntax
swift
while condition {
    // body
}

repeat {
    // body runs at least once
} while condition

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
// Declare a mutable variable `countdown`, initialized to `3`
var countdown = 3
// Keep looping while `countdown > 0` holds
while countdown > 0 {
    // Print "T-minus \(countdown)" to the console
    print("T-minus \(countdown)")
    countdown -= 1
}
// Print "Liftoff!" to the console
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
// Declare a mutable variable `attempts`, initialized to `0`
var attempts = 0
repeat {
    attempts += 1
    // Print "Attempt number \(attempts)" to the console
    print("Attempt number \(attempts)")
} while attempts < 3
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.