Swift while loop

The while loop evaluates a conditional statement and then repeatedly executes a block of code if the conditional statement is true.

Syntax :

1

2

3

4

5

6

whilecondition{

block of code tobe executed

}

Example of while loop in Swift

In this program, variable i starts at 0 and is incremented until it becomes 5.

1

2

3

4

5

6

7

8

9

10

vari=0;

whilei<5{

print(i)

i++

}

Swift repeat-while loop

In repeat-while loop the condition is at the end of the loop. That means that statements are executed at least once.

Syntax :

1

2

3

4

5

6

repeat{

block of code

}whilecondition

Example of repeat-while loop in Swift

1

2

3

4

5

6

7

8

9

vari=0;

repeat{

print(i)

i++

}whilei<5

Difference between while and repeat-while loop

The while loops check the conditional statement prior to executing the block of code the first time; therefore, all the variables in the conditional statements need to be initialized prior to executing the while loop.

The repeat-while loop runs through the loop block prior to checking the conditional statement for the first time; this means that we can initialize the variables in the conditional block of code.

Use of the repeat-while loop is preferred when the conditional statement is dependent on the code in the loop block.