Swift While Loop

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

Swift While Loop is used to execute a set of statements repeatedly based on a condition.

Syntax – Swift While Loop

Following is syntax of Swift While Loop in a program.

while boolean_expression {
    // set of statements
 }

boolean_expression is evaluated and if it returns true, the set of statements inside the while block are executed. And then the condition is checked again. If it returns true, the statements are executed again. The process repeats until the boolean_expression evaluates to false.

ADVERTISEMENT

Example 1 – Swift While Loop

Following example demonstrates the use of 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 while block.

main.swift

var i = 0

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

print("rest of the statements")

Output

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

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

Following example demonstrates while loop when the boolean expression evaluates to false in the first run.

main.swift

var i = 8

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

print("rest of the statements")

Output

$swift while_loop_example.swift
rest of the statements

Conclusion

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