Swift Loops โ€” while, repeat and Knowing When to Use Each ๐Ÿ”„

Published: (June 11, 2026 at 04:44 AM EDT)
4 min read
Source: Dev.to

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 > 0 before every iteration

  • Inside the loop we print the number and subtract 1

  • When countdown hits 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! ๐Ÿ‘‹

0 views
Back to Blog

Related posts

Read more ยป

The spec is in the wrong place

My day job is at a large tech company. Hundreds of engineering teams, and every one of them is somewhere different on AI adoption. Some are still treating codin...

The Heuristics Say Don't

A culture that only records its disasters ends up with a biased archive. Wars documented, plagues chronicled, collapses catalogued. The quiet decades go unwritt...