Swift Loops โ while, repeat and Knowing When to Use Each ๐
Source: Dev.to
In our last article we covered for loops โ perfect for when you know exactly how many times you need to repeat something. But what happens when you donโt know how many times youโll need to loop?
Thatโs where while and repeat loops come in. ๐ง
๐ The While Loop โ Run Until a Condition Is False
A while loop keeps running as long as a condition is true. The moment the condition becomes false, the loop stops:
while someCondition {
// code to repeat
}
Enter fullscreen mode
Exit fullscreen mode
No array needed. No range needed. Just a condition. Letโs see it in action:
var countdown = 10
while countdown > 0 {
print("\(countdown)...")
countdown -= 1
}
print("Blast off! ๐")
Enter fullscreen mode
Exit fullscreen mode
Output:
10...
9...
8...
7...
6...
5...
4...
3...
2...
1...
Blast off! ๐
Enter fullscreen mode
Exit fullscreen mode
Breaking it down:
We start with countdown = 10
-
The loop checks
countdown > 0before every iteration -
Inside the loop we print the number and subtract 1
-
When
countdownhits 0 the condition becomes false and the loop stops -
The final message prints after the loop ends
๐ฒ Random Numbers + While Loops โ A Perfect Combo
Hereโs where while loops really shine โ when you genuinely donโt know how many times youโll need to loop.
Swift gives us a fantastic tool called random(in:) that generates a random number within a range:
let id = Int.random(in: 1...1000) // random Int between 1 and 1000
let amount = Double.random(in: 0...1) // random Double between 0 and 1
Enter fullscreen mode
Exit fullscreen mode
Now letโs combine this with a while loop. Imagine youโre playing a game and need to keep rolling a dice until you land a critical hit โ a 20 on a 20-sided dice:
var roll = 0
while roll != 20 {
roll = Int.random(in: 1...20)
print("Rolled: \(roll)")
}
print("Critical hit! โ๏ธ")
Enter fullscreen mode
Exit fullscreen mode
Output (will vary every time):
Rolled: 7
Rolled: 13
Rolled: 4
Rolled: 19
Rolled: 20
Critical hit! โ๏ธ
Enter fullscreen mode
Exit fullscreen mode
Every time you run this code youโll get a different result โ sometimes lucky, sometimes not. This is impossible to replicate cleanly with a for loop because you simply donโt know how many rolls it will take. Thatโs the whole point of while. ๐ฏ
๐ฎ Another Example โ Grinding for Power
Letโs say youโre building an RPG and a character needs to keep training until their power level hits 9000:
var powerLevel = 1
var trainingRounds = 0
while powerLevel 0 && bossHealth > 0 {
let playerDamage = Int.random(in: 10...30)
let bossDamage = Int.random(in: 5...20)
bossHealth -= playerDamage
health -= bossDamage
print("Round \(round):")
print(" You dealt \(playerDamage) โ Boss health: \(max(0, bossHealth))")
print(" Boss dealt \(bossDamage) โ Your health: \(max(0, health))")
print()
round += 1
}
if health > 0 {
print("๐ You won in \(round - 1) rounds!")
} else {
print("๐ Defeated in \(round - 1) rounds. Try again!")
}
// Repeat loop โ generate a unique reward code
let usedCodes = [1111, 2222, 3333]
var rewardCode: Int
repeat {
rewardCode = Int.random(in: 1000...9999)
} while usedCodes.contains(rewardCode)
print("๐ Your reward code: \(rewardCode)")
Enter fullscreen mode
Exit fullscreen mode
๐ Wrap Up
Now you know all three loop types in Swift:
for โ when you know exactly how many times to loop
while โ when you loop until a condition becomes false, checked before each run
repeat โ when you always need at least one run, condition checked after
And remember โ always make sure your while or repeat condition will eventually become false, or youโll end up with an infinite loop! ๐
Next up weโll look at how to skip loop iterations and exit loops early using continue and break. See you there! ๐