Swift loops are designed to avoid common mistakes that cause errors. They help keep your program safe and stable by checking conditions automatically.
Why Swift loops are safe by default
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.
for number in 1...5 { print(number) }
while loop runs only while the count is above zero, stopping safely.var count = 3 while count > 0 { print(count) count -= 1 }
repeat-while loop runs the code first, then checks the condition to continue.var n = 1 repeat { print(n) n += 1 } while n <= 3
This program uses a for-in loop and a while loop to safely go through a list of fruits without errors.
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 }
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.
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.