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
counter
is less than10
then continue to iterate - If the
condition
variable istrue
then 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
}
}