while
A while loop uses the while keyword followed by a condition which evaluates to a Boolean.
let mut counter = 0;
let mut condition = true;
while counter < 10 && condition {
counter += 1;
if 5 < counter {
condition = false;
}
}
In the example above we use two conditions.
- If the
counteris less than10then continue to iterate - If the
conditionvariable istruethen continue to iterate
As long as both those conditions are true then the loop will iterate. In this case the loop will finish iterating once counter reaches the value of 6 because condition will be set to false.
Nested loops
Sway also allows nested while loops.
while true {
// computation here
while true {
// more computation here
}
}