0
0
Swiftprogramming~5 mins

While loop in Swift

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves you from writing the same code many times.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to keep checking if a task is done before moving on.
When you want to repeat an action but don't know in advance how many times.
When you want to process items until a list is empty.
Syntax
Swift
while condition {
    // code to repeat
}

The condition is a true or false check.

The code inside the braces runs only if the condition is true.

Examples
This loop prints numbers 1 to 3. It stops when count becomes 4.
Swift
var count = 1
while count <= 3 {
    print("Count is \(count)")
    count += 1
}
This loop runs 5 times and then stops by changing the condition.
Swift
var keepGoing = true
var tries = 0
while keepGoing {
    print("Trying...")
    tries += 1
    if tries == 5 {
        keepGoing = false
    }
}
Sample Program

This program counts down from 5 to 1 and then prints "Blast off!".

Swift
import Foundation

var number = 5
while number > 0 {
    print("Countdown: \(number)")
    number -= 1
}
print("Blast off!")
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever.

You can change the condition inside the loop to stop it when needed.

Summary

A while loop repeats code while a condition is true.

It is useful when you don't know how many times you need to repeat.

Always check that the loop will stop at some point.