Skip to Content
Learn
Loops
While Loop

Another loop we can use is the while loop. This loop allows us to continue iterating for as long as a condition remains true.

while condition {
  // Execute while condition remains true
}

while loops really shine for situations when we’re not exactly sure how long we need to loop for. For instance, let’s say we have a simple dice game that keeps a total of the numbers we’ve rolled. The goal of this game is to keep rolling until our total is at least 50. We know we’ll reach 50 eventually but we don’t know how many rolls we need to reach our stop condition. Coding it up, we get:

var total = 0 while total < 50 { let diceRoll = Int.random(in: 1...6) total += diceRoll }

Now let’s break down what’s going on:

  • The while keyword starts our loop and accepts a condition: total < 50.
  • Just like the for-in loop, after the condition is the body enclosed by a set of curly braces { }. The body’s code is executed during each iteration of the loop.
  • In the body, we declare let diceRoll with a value of Int.random(in: 1...6). In each iteration of the loop, we’re declaring a new diceRoll that has a random number from 1 to 6.
  • In addition to reassigning diceRoll, we’re also adding diceRoll to total. Eventually, total will be at least 50 and the loop terminates (ends).
  • It’s important to note that we’re increasing total because it’s related to our stopping condition. If we forgot to, our while would continue to run without any instructions to stop. This non-terminating loop is known as an infinite loop. It’ll continue to run and take up our computer’s resources until we manually force it to close. Therefore, remember to add a way for your loop to end.

Instructions

1.

In Guessing.swift, we have both a guess and a magicNum variable, each storing a random variable. We want to create a while loop that continues looping for as long as the values of both variables are different.

Under the variable definitions (but before the last print() statement):

  • Create a while loop.
  • Give the loop the condition guess != magicNum.
  • Reassign guess to Int.random(in: 1...10).
  • Also reassign magicNum to Int.random(in: 1...10).

Note: if you don’t reassign guess, you may end up in an infinite loop. 😱

2.

To find out what the values of guess and magicNum are during our loop, add a print() statement inside the loop that uses string interpolation to print out:

You guessed [guess], and the number was [magicNum].

Where [guess] and [magicNum] are replaced by the actual values of guess and magicNum.

Folder Icon

Take this course for free

Already have an account?