In Sway, control flow, variable assignment, and enums are important concepts that are frequently used when building smart contracts.
match
expression can be used to easily implement conditional checks and control flow in Sway.match
expression allows you to match a value against different code blocks.test_function
function, we use match
to determine the value of x
and execute the corresponding operation.match
expression to assign a value to a variable.test_function
function, we use match
to assign a value to the variable res
based on the value of x
.Option
type is an enum that contains two possible values: Some
and None
.test_function
function, we use match
to handle the Option
type variable y
.y
is Some
, we return its value plus 1; if y
is None
, we return 0.In the provided code, we define a smart contract named MyContract
with a function called test_function
that accepts two parameters: a u64
type x
and an Option<u64>
type y
.
match
expressions to determine the value of x
and execute the corresponding operation.match
expressions to assign a value to the variable res
based on the value of x
.match
expressions to handle the y
variable, and we return the corresponding result based on its value.The test_function
function of this smart contract ultimately returns a u64
type value. This simple example is intended to show you how to use control flow, variable assignment, and enums in Sway to build smart contracts. We hope this tutorial helps you better understand these concepts in Sway.
contract; // While loops // continue and break abi MyContract { fn example_1() -> u64; fn example_2() -> u64; fn example_3() -> u64; } impl MyContract for Contract { fn example_1() -> u64 { let mut total = 0; let mut i = 0; while i < 5 { i += 1; total += i; } // total = 1 + 2 + 3 + 4 + 5 total } fn example_2() -> u64 { // continue - sum odds let mut total = 0; let mut i = 0; while i < 5 { i += 1; // Skip if even if i % 2 == 0 { continue; } total += i; } // total = 1 + 3 + 5 total } fn example_3() -> u64 { // break let mut total = 0; let mut i = 0; while i < 5 { i += 1; if i > 3 { // Exit loop break; } total += i; } // total = 1 + 2 + 3 total } }