How to create while loop in Swift?

What is while loop?

Tested on: Xcode 12.2, Swift 5.3

While loop is another way of executing code multiple times by repeating your code. Another type of loop is For loop which covered previously. If you know another programming language, the concepts will be the same.

Note: Before you start you need to know Boolean, comparsion and logical.

  1. While Loop Syntax
  2. Repeat while loop





1. While Loop Syntax

A while loop repeats itself if the condition is true. To create a while loop, you need to use the while keyword and curly bracket. Between the bracket you add the code you want to repeat.

CONDITION can be a comparison operator when the outcome is either true or false.

Swift Code :

while CONDITION {
    // run code
}

The loop will check for the condition for every iteration. If the condition is true, the loop executes and moves on to another iteration and stop when it is false. Refer to the image below:

While Loop in Swift

As shown on the image, a while loop need to have a way to end the loop if not. It will result in an infinite loop and an infinite loop might not crash your program but it might freeze your computer. Look a the example below:

Swift Code :

let number = 1
while number > 0 {
    print("run")
}

The code causes an infinite loop because the number will always be 1 and the number is always bigger than zero. You can write an if statement inside to end it. The example code below will end the loop by resting the number to zero. (Of course, another way is to reduce the number in each loop.)

Swift Code :

let number = 1
while number > 0 {
   if number == 5 {
      number = 0
    }
    number += 1
    print("run")
}


2. Repeat while loop

The concept for repeats while loop is the same as the one above but the loop evaluated the condition at the end of the loop instead of beginning.

By doing this, the loop will always run once even if the condition is not true.

Swift Code :

var number = 5
repeat {
    number -= 1
} while number > 0