Swift While Loop

Swift While Loop

Loops are used to execute a block of code repeatedly as long as a certain condition is true.

A while loop evaluates its condition at the start of each pass through the loop.

It is best used when the number of iterations is not known before the loop begins.


The while Loop

The while loop checks a condition. If it is true, the code inside the block executes. It then checks the condition again, and repeats until the condition becomes false.

While Loop Example:

var counter = 1

while counter <= 5 { print("Count is \(counter)") counter += 1 // Don't forget to increase the counter! }

Warning: If you forget to update the variable being checked in the condition (like counter += 1), the loop will run forever. This is called an infinite loop!


The repeat-while Loop

The repeat-while loop is Swift's version of the do-while loop found in other languages.

The key difference is that it evaluates its condition at the end of each pass.

This guarantees that the code block will execute at least once, regardless of the condition.

Repeat-While Example:

var attempts = 1

repeat { print("Attempt number \(attempts)") attempts += 1 } while attempts < 1

In the example above, even though attempts < 1 is false immediately, the print statement executes exactly one time.


When to use which?


Exercise

Which loop guarantees that its code block will be executed at least once?