SWIFT

Swift While Loop: Syntax, Usage, and Examples

A while loop in Swift repeatedly runs a block of code as long as a condition remains true. It’s ideal when the number of iterations isn’t known in advance and depends on changing runtime values.


Basic Syntax

Swift offers two loop types: while and repeat-while.

Standard While Loop

while condition {
    // Code executes as long as condition is true
}
  • condition must be a Boolean expression.
  • The loop runs only if the condition is true before entering the block.

Example:

var counter = 3

while counter > 0 {
    print("Countdown: \(counter)")
    counter -= 1
}

This prints from 3 down to 1, then exits.


Repeat-While Loop

Swift doesn’t have a do while keyword, but the repeat-while structure behaves the same: it runs once before checking the condition.

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

Example:

var attempts = 1

repeat {
    print("Attempt \(attempts)")
    attempts += 1
} while attempts <= 3

When to Use While Loops

1. Waiting for a Condition to Change

var isConnected = false
var retries = 0

while !isConnected && retries < 5 {
    print("Trying to connect...")
    retries += 1
}

Useful for polling or retry logic.


2. Validating User Input

var input: String? = nil

while input != "yes" {
    print("Type 'yes' to continue:")
    input = readLine()
}

Perfect when waiting for specific input.


3. Simulating Processes

var temperature = 100.0

while temperature > 37.0 {
    print("Cooling down... Temp: \(temperature)")
    temperature -= 5.0
}

Use when simulating changing state.


Practical Examples

Loop Until a Condition Fails

var balance = 50

while balance > 0 {
    print("Current balance: \(balance)")
    balance -= 10
}

Infinite Loop With Break

var counter = 0

while true {
    if counter == 5 {
        break
    }
    print("Counter is \(counter)")
    counter += 1
}

Infinite loops are valid but require a reliable exit condition.


Repeat-While for Guaranteed Execution

var pin = ""

repeat {
    print("Enter your PIN:")
    pin = readLine() ?? ""
} while pin != "1234"

print("Access granted.")

Advanced Usage

Nested Loops

var i = 1

while i <= 3 {
    var j = 1
    repeat {
        print("Pair: (\(i), \(j))")
        j += 1
    } while j <= 2
    i += 1
}

You can freely combine while and repeat-while loops.


Using Break and Continue

let numbers = [1, 2, 3, 4, 5]
var index = 0

while index < numbers.count {
    let value = numbers[index]
    index += 1

    if value % 2 == 0 {
        continue  // Skip even numbers
    }

    print("Odd number: \(value)")
}
  • break exits the loop entirely.
  • continue skips the current iteration.

Looping Through Optionals

let optionalNames: [String?] = ["Ana", nil, "Leo", nil, "Kai"]
var i = 0

while i < optionalNames.count {
    if let name = optionalNames[i] {
        print("Name: \(name)")
    }
    i += 1
}

This pattern helps with safely unwrapping values during iteration.


Avoiding Infinite Loops

var i = 0

while i < 3 {
    print(i)
    // i += 1  // Don't forget to increment!
}

Make sure your loop variable updates, or the loop may never end.


Best Practices with Repeat-While

  • Use when code must run at least once (e.g., login prompts).
  • Keep conditions simple and expressive.
  • Avoid changing multiple variables inside the loop unless needed.

Looping Over Collections with Indexes

let colors = ["red", "green", "blue"]
var i = 0

while i < colors.count {
    print("Color: \(colors[i])")
    i += 1
}

This gives more control than a for-in loop—useful for skipping or jumping.


Summary

Swift’s while loop is perfect for situations where you can’t predict how many times to repeat a task. It’s useful for input validation, polling, simulations, or retry logic. When at least one execution is required, repeat-while ensures the loop runs once before checking the condition.

Compared to for-in, while gives more flexibility but also requires you to manage conditions, indices, and loop state carefully. With control tools like break, continue, and optional unwrapping, while remains one of the most powerful loop constructs in Swift.

Learn to Code in Swift for Free
Start learning now
button icon
To advance beyond this tutorial and learn Swift by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster