NEW: Learn to build the incredible iOS 15 Weather app today! >>

How to use a while loop to repeat work

Paul Hudson    @twostraws   

Updated for Xcode 13.2

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 Essential Developer

SPONSORED Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for iOS devs who want to become complete Senior iOS Developers.

Learn more

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

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.