Swift - Do-While Loop

Introduction

A variation of the While loop is the Do-While loop.

The Do-While loop has the following syntax:


do {
    statement (s)
} while condition

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

Demo

index = 0
do {//w ww.  ja  v a2s. c  om
    print(index++)
} while (index<5)

The Do-While executes the block of statement(s) enclosed by the pair of braces {} first before checking the condition to decide if the looping will continue.

If the condition evaluates to true , the loop continues.

If it evaluates to false , then the loop exits.

Within a Do-While loop execute at least once, since their condition is evaluated at the end of the block.

Exercise