Swift - Statement While Loop

Introduction

In addition to the For loop, Swift provides the While loop.

The While loop executes a block of statements repeatedly as long as the specified condition is true:


while condition {
    statement (s)
}

The following code outputs the series of numbers 0 to 4:

Demo

var index = 0
while index<5 {
   print(index++)/* www .  j  a  v a2s  .  c  o  m*/
}

Before the first iteration starts, the While loop checks the value of index.

If it is less than 5, it will enter the loop and execute the statement(s) within.

Within the block, you increment the value of index after outputting it to the screen.

The condition is then checked again to see it is evaluates to true.

As long as it evaluates to true, the loop is repeated. When index finally becomes 5, the While loop ends.

A while loop repeatedly runs code while a certain condition remains true. For example:

Demo

var countDown = 5 
while countDown > 0 { 
       countDown -= 1 //from  ww  w . ja v  a  2  s  . co  m
} 
print(countDown) // 0

Result

Here, while loops check to see if the condition at the start of the loop evaluates to true.

If it does, they run the code and then return to the start.

In addition to the regular while loop, the repeat-while loop runs the code at least once and then checks the condition.

Exercise