Swift While Loop

Execute code repeatedly while conditions are true

⏳ What is While Loop?

Swift while loops execute code repeatedly as long as a condition remains true. They're perfect for situations where you don't know the exact number of iterations needed beforehand.


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

Output:

Count: 1

Count: 2

Count: 3

While Loop Characteristics

Condition First

Checks condition before execution

while condition {
    // May not execute at all
}
🔄

Unknown Iterations

Perfect for uncertain loop counts

while !found {
    // Keep searching
}
⚠️

Infinite Risk

Can run forever if condition never changes

while true {
    // Dangerous!
    break // Need exit
}
🎯

Variable Control

Loop variable must be managed manually

var i = 0
while i < 10 {
    i += 1 // Don't forget!
}

🔹 Basic While Loop Syntax

The condition is evaluated before each iteration:

var number = 10

while number > 0 {
    print("Countdown: \(number)")
    number -= 1
}
print("Launch! 🚀")

// Example with boolean condition
var gameRunning = true
var lives = 3

while gameRunning && lives > 0 {
    print("Playing game... Lives: \(lives)")
    lives -= 1
    if lives == 0 {
        gameRunning = false
    }
}

Output:

Countdown: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Launch! 🚀

Playing game... Lives: 3

Playing game... Lives: 2

Playing game... Lives: 1

🔹 While vs For-In Comparison

Choose the right loop for your situation:

// For-in: Known number of iterations
for i in 1...5 {
    print("For-in: \(i)")
}

// While: Unknown number of iterations
var attempts = 0
var success = false

while !success && attempts < 5 {
    attempts += 1
    print("Attempt \(attempts)")
    // Simulate random success
    success = attempts == 3 // Success on 3rd attempt
}

if success {
    print("Success after \(attempts) attempts!")
} else {
    print("Failed after \(attempts) attempts")
}

Output:

For-in: 1, 2, 3, 4, 5

Attempt 1

Attempt 2

Attempt 3

Success after 3 attempts!

🔹 Common While Loop Patterns

Typical use cases for while loops:

// Pattern 1: Input validation
var userInput = ""
while userInput.isEmpty {
    print("Please enter your name:")
    userInput = "John" // Simulated input
}

// Pattern 2: Processing until empty
var tasks = ["Task 1", "Task 2", "Task 3"]
while !tasks.isEmpty {
    let task = tasks.removeFirst()
    print("Completed: \(task)")
}

// Pattern 3: Search with condition
let numbers = [2, 4, 7, 8, 10]
var index = 0
var found = false

while index < numbers.count && !found {
    if numbers[index] % 2 == 1 { // Looking for odd number
        print("Found odd number: \(numbers[index]) at index \(index)")
        found = true
    }
    index += 1
}

Output:

Please enter your name:

Completed: Task 1

Completed: Task 2

Completed: Task 3

Found odd number: 7 at index 2

🧠 Test Your Knowledge

When is a while loop preferred over a for-in loop?