Swift While Loop

In this Swift tutorial, you will learn about the Swift while loop with some examples.

In the programming world, a loop is used to repeat a block of code multiple times. For example, you can print the “Hello World” text 100 times or even 1000 times.

Syntax of the Swift while loop

Below is the given syntax for Swift while loop:

while (condition){
  // code block of body

In the above syntax, the while loop checks the condition inside the parenthesis (). If the condition becomes true, the code inside the loop will be executed.

The process of running the code inside the loop will continue until the condition become false. When the condition becomes false, the code inside the loop will not run anymore and thus the loop will stop.

Flowchart of a while loop

Below is given the given flowchart diagram of the while loop:

While Loop Diagram
Working of while loop with diagram

The above diagram shows how a while loop works.

Examples of Swift while loop

Now let’s see the example of while loops in Swift programming.

Example 1:

// Declaring the variables
var i = 0, j = 7

// while loop from i = 0 to 7
while (i <= j) {
   i = i + 1



In the above example, we are evaluating if i is less than or equal to j in the parenthesis of the while loop (i <= j). Inside the while loop, we are gradually increasing i value by 1 each time the code block of the while loop run.

When the value of i will be greater than the j value, the condition will become false as our condition only evaluates if i is less than or equal to j. So the loop will close.

Example 2: Iterate over an array using the while loop

You can also iterate over a Swift array using the while loop as you can see in the example below:

var colors = ["Green", "Red", "Yellow", "Black"]
var i = 0
while i < colors.count {
    let color = colors[i] //access ith element of colors array
    i += 1



As you can see in the above code, we have an array colors that contains some names of colors as the array elements. Using the while loop, we are able to iterate over the array and print each name of the color.

Here we have first counted the number of array elements and then checked running the while loop with a condition until i value becomes greater than the value of array length.