Skip to main content

Swift Repeat While Loops

In Swift programming, loop structures are essential for executing a block of code multiple times. While the for and while loops are familiar to many programmers, Swift also offers the repeat-while loop — a variation that ensures a code block runs at least once before checking whether it should continue.

What is a Repeat While Loop?

The repeat-while loop in Swift is similar to the do-while loop found in other programming languages. It has a specific characteristic that distinguishes it from regular while loops:

  • It executes a block of code first
  • Then it evaluates a condition
  • If the condition is true, it repeats the process
  • If the condition is false, it exits the loop

This guarantees that the code inside the loop will execute at least once, regardless of the condition's initial value.

Basic Syntax

Here's the basic syntax of a repeat-while loop in Swift:

swift
repeat {
// Code to be executed at least once
} while condition

How Repeat While Works

Let's explore how a repeat-while loop functions with a simple example:

swift
var counter = 1

repeat {
print("Current value is \(counter)")
counter += 1
} while counter <= 5

Output:

Current value is 1
Current value is 2
Current value is 3
Current value is 4
Current value is 5

In this example:

  1. We initialize a counter variable with value 1
  2. The code inside the repeat block executes, printing the current value and incrementing the counter
  3. After executing the block, Swift checks if counter <= 5
  4. If the condition is true, the loop repeats
  5. Once counter becomes 6, the condition becomes false, and the loop terminates

Repeat While vs Regular While Loop

The key difference between repeat-while and regular while loops is when the condition is evaluated:

swift
// Example with repeat-while
var number = 10

repeat {
print("repeat-while: \(number)")
number -= 1
} while number > 0

// Reset number
number = 10

// Example with regular while
while number > 0 {
print("regular while: \(number)")
number -= 1
}

Output:

repeat-while: 10
repeat-while: 9
repeat-while: 8
repeat-while: 7
repeat-while: 6
repeat-while: 5
repeat-while: 4
repeat-while: 3
repeat-while: 2
repeat-while: 1
regular while: 10
regular while: 9
regular while: 8
regular while: 7
regular while: 6
regular while: 5
regular while: 4
regular while: 3
regular while: 2
regular while: 1

Both loops produce similar output when the initial condition is true. But what if the condition is initially false?

swift
var x = 0

// repeat-while when condition is initially false
repeat {
print("This will be executed once")
x += 1
} while x > 10

// regular while when condition is initially false
while x > 10 {
print("This will never be executed")
x += 1
}

Output:

This will be executed once

As you can see, the repeat-while loop executed once despite the condition being false, while the regular while loop was skipped entirely.

Practical Examples

Example 1: Input Validation

repeat-while loops are perfect for input validation where you want to keep asking until valid input is provided:

swift
import Foundation

func getUserAge() -> Int {
var age: Int?
var isValidInput = false

repeat {
print("Please enter your age:")
if let input = readLine(), let userAge = Int(input) {
if userAge > 0 && userAge < 120 {
age = userAge
isValidInput = true
} else {
print("Please enter a valid age between 1 and 120.")
}
} else {
print("Invalid input. Please enter a number.")
}
} while !isValidInput

return age!
}

// Usage:
// let userAge = getUserAge()
// print("Your age is \(userAge)")

In this example, the program will continue asking for the user's age until valid input is provided.

Example 2: Menu System

repeat-while loops can be used to create simple menu systems:

swift
import Foundation

func displayMenu() {
var choice = 0

repeat {
print("\n--- Calculator Menu ---")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division")
print("5: Exit")
print("Enter your choice (1-5):")

if let input = readLine(), let menuChoice = Int(input) {
choice = menuChoice

switch choice {
case 1:
print("You selected Addition")
// Add addition functionality
case 2:
print("You selected Subtraction")
// Add subtraction functionality
case 3:
print("You selected Multiplication")
// Add multiplication functionality
case 4:
print("You selected Division")
// Add division functionality
case 5:
print("Exiting calculator...")
default:
print("Invalid selection. Please try again.")
}
} else {
print("Invalid input. Please enter a number between 1 and 5.")
}
} while choice != 5
}

// Usage:
// displayMenu()

This menu system will continue running until the user selects option 5 to exit.

Example 3: Game Loop

Game development often uses loops that run at least once:

swift
func simpleNumberGame() {
import Foundation

let targetNumber = Int.random(in: 1...100)
var guessCount = 0
var hasWon = false

print("I'm thinking of a number between 1 and 100.")

repeat {
print("Enter your guess:")

if let input = readLine(), let guess = Int(input) {
guessCount += 1

if guess < targetNumber {
print("Too low!")
} else if guess > targetNumber {
print("Too high!")
} else {
hasWon = true
print("Correct! You guessed the number in \(guessCount) attempts.")
}
} else {
print("That's not a valid number.")
}
} while !hasWon
}

// Usage:
// simpleNumberGame()

This guessing game continues running until the player correctly guesses the random number.

When to Use Repeat While Loops

repeat-while loops are particularly useful when:

  1. You need to execute code at least once regardless of conditions
  2. Validating user input
  3. Creating menu systems
  4. Processing data where you need to perform operations before checking if more processing is needed
  5. Game development for game loops that should run at least once

Common Pitfalls to Avoid

  1. Infinite Loops: Ensure your loop condition will eventually become false
swift
// Infinite loop - will crash or hang your program
repeat {
print("This will run forever")
} while true

// Fix: add a condition or break statement
var counter = 0
repeat {
print("This will run 5 times")
counter += 1
if counter >= 5 {
break
}
} while true
  1. Forgetting to Update the Condition: Always ensure variables in your condition are updated inside the loop
swift
var x = 0
// Wrong: x is never incremented, creating an infinite loop
repeat {
print("Iteration")
// Missing x += 1
} while x < 5

// Correct:
x = 0
repeat {
print("Iteration")
x += 1 // Important!
} while x < 5

Summary

The repeat-while loop in Swift provides a way to execute code at least once before checking a condition. This makes it different from the regular while loop, which checks the condition first. The repeat-while construct is particularly useful for input validation, menu systems, and any scenario where you need to guarantee that code executes at least once.

Key points to remember:

  • The loop body executes before the condition is checked
  • It always runs at least once
  • The syntax is: repeat { code } while condition
  • Be careful to avoid infinite loops by ensuring the condition will eventually become false

Additional Resources and Exercises

Exercises

  1. User Authentication: Create a simple login system that keeps asking for a password until the correct one is entered.

  2. Number Summation: Write a program that asks the user for numbers to add together. Continue asking until they enter 0, then display the total sum.

  3. Dice Roller: Create a dice rolling simulator that rolls until a specific number appears. Count how many rolls it takes.

  4. Converting a while loop: Take the following while loop and convert it to a repeat-while loop:

swift
var countdown = 10
while countdown >= 0 {
print("\(countdown)...")
countdown -= 1
}
print("Blast off!")

Further Reading

Remember, practice is key to mastering loop structures in Swift. Try creating your own examples and experimenting with different conditions to solidify your understanding of repeat-while loops!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)