Swift Loops

Repeat code efficiently with Swift loop structures

🔄 What are Swift Loops?

Swift loops allow you to execute code repeatedly until a condition is met. They help automate repetitive tasks and iterate through collections efficiently, making your code cleaner and more maintainable.


// Simple loop example
for i in 1...3 {
    print("Count: \(i)")
}
                                    

Output:

Count: 1

Count: 2

Count: 3

Types of Swift Loops

🔢

For-In Loop

Iterate through sequences

for item in array {
    print(item)
}

While Loop

Loop while condition is true

while condition {
    // code here
}
🔁

Repeat-While

Execute at least once

repeat {
    // code here
} while condition
🎯

Loop Control

Break and continue statements

for i in 1...10 {
    if i == 5 { break }
    print(i)
}

🔹 For-In Loop Basics

The most common loop for iterating through collections:

let fruits = ["apple", "banana", "orange"]

for fruit in fruits {
    print("I like \(fruit)s! 🍎")
}

// Loop through a range
for number in 1...5 {
    print("Number: \(number)")
}

Output:

I like apples! 🍎

I like bananas! 🍎

I like oranges! 🍎

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

🔹 While Loop Example

Execute code while a condition remains true:

var countdown = 5

while countdown > 0 {
    print("Countdown: \(countdown)")
    countdown -= 1
}
print("Blast off! 🚀")

Output:

Countdown: 5

Countdown: 4

Countdown: 3

Countdown: 2

Countdown: 1

Blast off! 🚀

🔹 Loop Control Statements

Control loop execution with break and continue:

// Using continue to skip even numbers
for i in 1...10 {
    if i % 2 == 0 {
        continue // Skip even numbers
    }
    print("Odd number: \(i)")
}

// Using break to exit early
for i in 1...10 {
    if i == 6 {
        break // Stop at 6
    }
    print("Number: \(i)")
}

Output:

Odd number: 1

Odd number: 3

Odd number: 5

Odd number: 7

Odd number: 9

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

🧠 Test Your Knowledge

Which loop guarantees at least one execution?