Skip to main content

Swift While Loop

Loops are a fundamental part of programming, allowing you to execute code repeatedly based on certain conditions. In this lesson, we'll explore the while loop in Swift, one of the primary looping constructs available to control the flow of your programs.

What is a While Loop?

A while loop executes a block of code repeatedly as long as a specified condition remains true. Think of it as saying "keep doing this while something is true."

The basic syntax of a while loop in Swift is:

swift
while condition {
// Code to execute as long as condition is true
}

The loop first evaluates the condition. If it's true, the code inside the curly braces executes. After execution, it goes back to the condition and checks again. This process repeats until the condition evaluates to false.

Simple While Loop Example

Let's start with a basic example:

swift
var counter = 1

while counter <= 5 {
print("Count is: \(counter)")
counter += 1
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

How this works:

  1. We initialize a variable counter with the value 1
  2. The while loop checks if counter <= 5 (which is true initially)
  3. It executes the code block, printing the current value
  4. It increments the counter by 1
  5. It checks the condition again and repeats steps 3-4 until the condition becomes false

Important: Avoiding Infinite Loops

One common mistake when using while loops is creating an infinite loop, where the condition never becomes false. For example:

swift
var counter = 1

while counter > 0 {
print("This will run forever!")
// Counter never changes, so condition is always true
}

To avoid infinite loops, always make sure:

  • Your condition will eventually become false
  • You update the variables that affect the condition within the loop

Practical Example: Input Validation

Let's see how a while loop can be used for input validation:

swift
import Foundation

var userInput = ""
var validInput = false

while !validInput {
print("Please enter a number between 1 and 10:")
userInput = readLine() ?? ""

if let number = Int(userInput), number >= 1 && number <= 10 {
print("Thank you! You entered a valid number: \(number)")
validInput = true
} else {
print("Invalid input. Try again.")
}
}

In this example, the loop continues to prompt the user until they enter a valid number between 1 and 10.

While Loops with Collections

While loops can also be used to iterate through collections like arrays:

swift
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
var index = 0

while index < fruits.count {
print("Fruit at index \(index): \(fruits[index])")
index += 1
}

Output:

Fruit at index 0: Apple
Fruit at index 1: Banana
Fruit at index 2: Cherry
Fruit at index 3: Date
Fruit at index 4: Elderberry

Note:

For simple array iteration, a for-in loop is usually more appropriate, but there are situations where while loops offer more flexibility.

Repeat-While Loop

Swift also provides a variant called the repeat-while loop (known as a do-while loop in many other languages). The key difference is that a repeat-while loop always executes the code block at least once before checking the condition.

swift
var counter = 1

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

Output:

Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5

Even if the condition is initially false, the code will execute once:

swift
var number = 10

repeat {
print("This will execute once even though the condition is false")
number += 1
} while number < 10

Output:

This will execute once even though the condition is false

Real-World Example: Game Development

In games, while loops are often used for game loops that continue until certain conditions are met:

swift
var playerHealth = 100
var gameOver = false

while !gameOver {
// Simulate player taking damage
playerHealth -= Int.random(in: 10...20)

print("Player took damage! Health: \(playerHealth)")

// Check if game should end
if playerHealth <= 0 {
gameOver = true
print("Game Over!")
}

// In a real game, this would process input, update game state, render, etc.
}

Sample Output:

Player took damage! Health: 81
Player took damage! Health: 67
Player took damage! Health: 49
Player took damage! Health: 30
Player took damage! Health: 19
Player took damage! Health: -1
Game Over!

When to Use While Loops

Use while loops when:

  1. You don't know in advance how many iterations you need
  2. You need to continue a process until a specific condition is met
  3. You want to implement an event loop that runs until terminated
  4. You need to validate user input until it meets certain criteria

Summary

The while loop is a powerful control flow construct in Swift that allows you to:

  • Execute code repeatedly while a condition remains true
  • Process data until it meets specific criteria
  • Create game loops or event-driven processes

Remember to always include a way for your loop condition to eventually become false to avoid infinite loops. The variant repeat-while guarantees that the code executes at least once before checking the condition.

Exercises

  1. Write a while loop that prints all even numbers from 2 to 20.
  2. Create a guessing game where the program picks a random number between 1 and 100, and the user tries to guess it. Use a while loop to keep prompting the user until they guess correctly.
  3. Write a program that uses a while loop to find the smallest power of 2 that is greater than 1000.
  4. Implement a simple calculator program that keeps running until the user chooses to exit.

Additional Resources

Happy coding!



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