In Sway, while loops, continue, and break are key concepts for controlling loop structures.
example_1
function, we use a while loop to calculate the sum of integers from 1 to 5.example_2
function, we use a while loop and continue to calculate the sum of odd numbers from 1 to 5.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.
example_1
function uses a while loop to calculate the sum of integers from 1 to 5.example_2
function uses a while loop and continue to calculate the sum of odd numbers from 1 to 5.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.
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); } }