0
0
Swiftprogramming~5 mins

Why Swift loops are safe by default

Choose your learning style9 modes available
Introduction

Swift loops are designed to avoid common mistakes that cause errors. They help keep your program safe and stable by checking conditions automatically.

When you want to repeat a task a certain number of times without errors.
When you need to go through each item in a list safely.
When you want to avoid accidentally running a loop forever.
When you want the program to stop looping if something unexpected happens.
When you want clear and easy-to-read code that prevents mistakes.
Syntax
Swift
for item in collection {
    // code to run
}

while condition {
    // code to run
}

repeat {
    // code to run
} while condition

Swift checks the loop conditions before running the code inside, so it won't run if the condition is false.

Using for-in loops helps avoid errors like going past the end of a list.

Examples
This loop prints numbers from 1 to 5 safely, no risk of going out of range.
Swift
for number in 1...5 {
    print(number)
}
This while loop runs only while the count is above zero, stopping safely.
Swift
var count = 3
while count > 0 {
    print(count)
    count -= 1
}
This repeat-while loop runs the code first, then checks the condition to continue.
Swift
var n = 1
repeat {
    print(n)
    n += 1
} while n <= 3
Sample Program

This program uses a for-in loop and a while loop to safely go through a list of fruits without errors.

Swift
let fruits = ["Apple", "Banana", "Cherry"]

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

var index = 0
while index < fruits.count {
    print("Fruit at index \(index) is \(fruits[index])")
    index += 1
}
OutputSuccess
Important Notes

Swift loops automatically check conditions before running, preventing common mistakes like infinite loops or out-of-range errors.

Using for-in loops with collections is safer than using index-based loops because Swift handles the range for you.

Summary

Swift loops check conditions before running to keep your code safe.

for-in loops help avoid errors by managing collection ranges automatically.

Loops stop safely when conditions are no longer true, preventing crashes or infinite loops.