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.
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.
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.
var count = 1 while count <= 3 { print("Count is \(count)") count += 1 }
var keepGoing = true var tries = 0 while keepGoing { print("Trying...") tries += 1 if tries == 5 { keepGoing = false } }
This program counts down from 5 to 1 and then prints "Blast off!".
import Foundation var number = 5 while number > 0 { print("Countdown: \(number)") number -= 1 } print("Blast off!")
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.
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.
while loop do in Swift?var count = 3
while count > 0 {
print(count)
count -= 1
}var i = 1
while i < 5 {
print(i)
}Pass the test and this pattern moves unknown