Swift: While Loop

While Loop in Swift:

The while loop in Swift is another loop that allows us to iterate indefinitely as long as a condition is true.

while condition {
  // run while condition remains true

while loops are particularly useful when we don’t know how long we need to loop for. Let’s say we have a simple dice game where the count of the numbers we’ve rolled is kept. The objective of this game is to keep rolling until we reach a count of 30. We know we’ll get to 30 eventually, but we’re not sure how many rolls we’ll need to get there. Coding it up we get:

var count = 0;
while count < 30 {
  let rollDice = Int.random(in: 1...6);
  count += rollDice;

Let’s take a look at what’s going on:

  • Our loop is started with the while keyword, which accepts the condition: count < 30.
  • The body is enclosed by a set of curly braces {} after the condition, just like the forin loop. During each iteration of the loop, the code in the body is executed.
  • We declare let rollDice with a value of Int.random(in: 1...6) in the body. We declare a new rollDice with a random number between 1 and 6 in each iteration of the loop.
  • We’re reassigning rollDice as well as adding rollDice to count. The loop will eventually come to an end when the count is at least 30.
  • It’s worth noting that we’re increasing the count because of our stopping condition. If we forget, our while will keep running until we tell it to stop. An infinite loop is a non-terminating loop with no end. Until we manually close it, it will continue to run and consume our computer’s resources. As a result, make sure your loop has a way to end.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: