Swift Repeat While Loop

Welcome to Swift Tutorial. In this tutorial, we will learn about Swift Repeat While Loop with examples.

Swift Repeat While Loop is used to execute a set of statements repeatedly based on a condition. Repeat While Loop is different from While Loop based on the fact that the expression is evaluated after executing the set of statements. Repeat While Loop ensures that the set of statements gets executed atleast once irrespective of the boolean_expression’s value.

Syntax – Swift Repeat While Loop

Following is syntax of Repeat While Loop in a swift program.

</>
Copy
 repeat {
    // set of statements
 } while( boolean_expression )

First the set of statements inside repeat block are executed. Then boolean_expression is evaluated and if it returns true, the set of statements inside the repeat block are executed again. Then boolean_expression is evaluated again and the process continues. The loop is broken only when the boolean_expression is evaluated to false.

Example 1 – Swift Repeat While Loop

In this example, we will use repeat while loop to iterate a set of statements while i<5. Observe that we are modifying the state of the program by incrementing i in repeat block.

main.swift

</>
Copy
var i = 1

repeat {
   print("i : \(i)")
   i = i + 1
} while( i<5 )

print("rest of the statements")

Output

$swift repeat_while_loop_example.swift
i : 1
i : 2
i : 3
i : 4
rest of the statements

Example 2 – Swift While Loop – Condition is false right away

In this example, we will use repeat while loop when the boolean expression evaluates to false in the first run.

main.swift

</>
Copy
var i = 8

repeat {
   print("i : \(i)")
   i = i + 1
} while( i<5 )

print("rest of the statements")

Output

$swift repeat_while_loop_example.swift
i : 8
rest of the statements

See the beauty. The statements inside the repeat block are executed atleast once even when the boolean expression evaluates to false for the first time.

Conclusion

In this Swift Tutorial, we have learned about Swift Repeat While Loop with syntax and examples covering different scenarios.