Swift Repeat While

Execute code at least once with repeat-while loops

🔁 What is Repeat-While?

Swift repeat-while loops execute code at least once before checking the condition. Unlike while loops, they guarantee the code block runs minimum once, making them perfect for validation scenarios.


// Basic repeat-while loop
var count = 1
repeat {
    print("Count: \(count)")
    count += 1
} while count <= 3
                                    

Output:

Count: 1

Count: 2

Count: 3

Repeat-While Features

🎯

Execute First

Code runs before condition check

repeat {
    // Always runs once
} while condition

Guaranteed Execution

Minimum one iteration always

repeat {
    print("Hello")
} while false // Still prints
🔍

Input Validation

Perfect for user input scenarios

repeat {
    input = getInput()
} while input.isEmpty
🎮

Game Loops

Ideal for game or menu systems

repeat {
    playGame()
} while wantToPlayAgain

🔹 Repeat-While vs While

See the difference in execution behavior:

// While loop - may not execute
var condition = false
print("While loop:")
while condition {
    print("This won't print")
}

// Repeat-while - always executes once
print("Repeat-while loop:")
repeat {
    print("This will print once!")
} while condition

// Practical example: Menu system
var choice = 0
repeat {
    print("Menu:")
    print("1. Play Game")
    print("2. Settings") 
    print("3. Exit")
    choice = 3 // Simulated user choice
    print("You chose: \(choice)")
} while choice != 3

Output:

While loop:

Repeat-while loop:

This will print once!

Menu:

1. Play Game

2. Settings

3. Exit

You chose: 3

🔹 Input Validation Example

Perfect for ensuring valid user input:

// Password validation
var password = ""
var attempts = 0

repeat {
    attempts += 1
    print("Attempt \(attempts): Enter password")
    password = "secret123" // Simulated input
    
    if password.count < 8 {
        print("Password too short! Must be at least 8 characters.")
        password = "" // Reset to continue loop
    } else if !password.contains(where: { $0.isNumber }) {
        print("Password must contain at least one number!")
        password = "" // Reset to continue loop
    }
} while password.isEmpty && attempts < 3

if !password.isEmpty {
    print("Password accepted! ✅")
} else {
    print("Too many failed attempts! ❌")
}

Output:

Attempt 1: Enter password

Password accepted! ✅

🔹 Game Loop Pattern

Common pattern for interactive applications:

// Simple number guessing game
let secretNumber = 7
var guess = 0
var gameWon = false

repeat {
    print("Guess a number between 1 and 10:")
    guess = Int.random(in: 1...10) // Simulated guess
    print("You guessed: \(guess)")
    
    if guess == secretNumber {
        print("Congratulations! You won! 🎉")
        gameWon = true
    } else if guess < secretNumber {
        print("Too low! Try higher.")
    } else {
        print("Too high! Try lower.")
    }
} while !gameWon

// Another game loop with play again option
var playAgain = true
repeat {
    print("Playing a round...")
    print("Round completed!")
    
    // Simulate asking to play again
    playAgain = false // Set to false to exit
    print("Play again? \(playAgain ? "Yes" : "No")")
} while playAgain

Output:

Guess a number between 1 and 10:

You guessed: [random number]

[Feedback based on guess]

Playing a round...

Round completed!

Play again? No

🧠 Test Your Knowledge

What's the key difference between while and repeat-while?