Conditional Loop in Swift- Do-While

The other variation of the while loop, known as the dowhile loop, performs a single pass through the loop block first, before considering the loop’s condition. It then continues to repeat the loop until the condition isfalse.

Here’s the syntax of a dowhile loop:

Here’s the Snakes and Ladders example again, written as a dowhile loop rather than a while loop.

The values of finalSquare, board, square, and diceRoll are initialized in exactly the same way as with a whileloop.  In this version of the game, the first action in the loop is to check for a ladder or a snake. No ladder on the board takes the player straight to square 25. So it is not possible to win the game by moving up a ladder. Therefore, it is safe to check for a snake or a ladder as the first action in the loop. At the start of the game, the player is on “square zero”. board[0] always equals 0, and has no effect:

After the code checks for snakes and ladders, the dice is rolled, and the player is moved forward by diceRollsquares. The current loop execution then ends. The loop’s condition (while square < finalSquare) is the same as before. But this time it is not evaluated until the end of the first run through the loop. The structure of the dowhile loop is better suited to this game than the while loop in the previous example.

In the dowhile loop above, square += board[square] is always executed immediately after the loop’s while condition confirms that square is still on the board. This behavior removes the need for the array bounds check seen in the earlier version of the game.

Next we will learn about the If Statement in Swift.