Control Flow - While Loop

In Sway, while loops, continue, and break are key concepts for controlling loop structures.

  1. while Loops (While Loops):
    • while loops allow you to repeatedly execute a block of code until a certain condition is no longer true.
    • In the example_1 function, we use a while loop to calculate the sum of integers from 1 to 5.
  2. continue and break:
    • The continue statement allows you to skip the remaining part of the current loop iteration and start the next iteration.
    • The break statement allows you to completely exit the loop, skipping the remaining part of the loop.
    • In the example_2 function, we use a while loop and continue to calculate the sum of odd numbers from 1 to 5.
    • In the example_3 function, we use a while loop and break to calculate the sum of integers from 1 to 3.

In the provided code, we define a smart contract named MyContract with three functions named example_1, example_2, and example_3, each returning a u64 type value.

  • The example_1 function uses a while loop to calculate the sum of integers from 1 to 5.
  • The example_2 function uses a while loop and continue to calculate the sum of odd numbers from 1 to 5.
  • The example_3 function uses a while loop and break to calculate the sum of integers from 1 to 3.

The example_1, example_2, and example_3 functions of this smart contract return 15, 9, and 6, respectively. This simple example is intended to show you how to use while loops, continue, and break in Sway to control loop structures. We hope this tutorial helps you better understand these control structures in Sway.

All Examples
contract;

use std::logging::log;

abi MyContract {
    fn test_func(msg: str[4]);
}

impl MyContract for Contract {
    fn test_func(msg: str[4]) {
        log(msg);
    }
}