UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to use a while loop to repeat work

Paul Hudson    @twostraws   

Updated for Xcode 15

Swift has a second kind of loop called while: provide it with a condition, and a while loop will continually execute the loop body until the condition is false.

Although you’ll still see while loops from time to time, they aren’t as common as for loops. As a result, I want to cover them so you know they exist, but let’s not dwell on them too long, okay?

Here’s a basic while loop to get us started:

var countdown = 10

while countdown > 0 {
    print("\(countdown)…")
    countdown -= 1
}

print("Blast off!")

That creates an integer counter starting at 10, then starts a while loop with the condition countdown > 0. So, the loop body – printing the number and subtracting 1 – will run continually until countdown is equal to or below 0, at which point the loop will finish and the final message will be printed.

while loops are really useful when you just don’t know how many times the loop will go around. To demonstrate this, I want to introduce you to a really useful piece of functionality that Int and Double both have: random(in:). Give that a range of numbers to work with, and it will send back a random Int or Double somewhere inside that range.

For example, this creates a new integer between 1 and 1000

let id = Int.random(in: 1...1000)

And this creates a random decimal between 0 and 1:

let amount = Double.random(in: 0...1)

We can use this functionality with a while loop to roll some virtual 20-sided dice again and again, ending the loop only when a 20 is rolled – a critical hit for all you Dungeons & Dragons players out there.

Here’s the code to make that happen:

// create an integer to store our roll
var roll = 0

// carry on looping until we reach 20
while roll != 20 {
    // roll a new dice and print what it was
    roll = Int.random(in: 1...20)
    print("I rolled a \(roll)")
}

// if we're here it means the loop ended – we got a 20!    
print("Critical hit!")

You’ll find yourself using both for and while loops in your own code: for loops are more common when you have a finite amount of data to go through, such as a range or an array, but while loops are really helpful when you need a custom condition.

Hacking with Swift is sponsored by Proxyman

SPONSORED Proxyman: A high-performance, native macOS app for developers to easily capture, inspect, and manipulate HTTP/HTTPS traffic. The ultimate tool for debugging network traffic, supporting both iOS and Android simulators and physical devices.

Start for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.