In Sway, if-else statements and if let are key control structures used for conditional judgments and code branching.
if-else statements allow you to execute different code blocks based on a certain condition.else if to add additional conditional checks, which can avoid duplicating code blocks.else block will be executed.if let is a pattern matching expression in Sway that allows you to destructure a value based on a condition.Option or Result types to simplify error handling and value parsing.In the provided code, we define a smart contract named MyContract with a function called test_func that accepts a u64 type parameter and returns a u64 type value.
if-else statements to check the value of the parameter x and perform different operations based on its size.if let to destructure the parameter x and calculate the value of a variable y based on its value.if-else statement where the condition expression directly returns a value, rather than containing multiple code blocks.The test_func function of this smart contract ultimately returns the value of the variable y. This simple example is intended to show you how to use if-else statements and if let in Sway for conditional judgments and code branching. We hope this tutorial helps you better understand these control structures in Sway.
contract;
// Control flow
// Assign variable
// Enum
abi MyContract {
fn test_function(x: u64, y: Option) -> u64;
}
fn do_something() {}
fn do_something_else() {}
impl MyContract for Contract {
fn test_function(x: u64, y: Option) -> u64 {
// Control flow
match x {
0 => do_something(),
_ => do_something_else(),
}
// Assign variable
let res: str = match x {
0 => "a",
1 => "b",
2 => "c",
_ => "d",
};
// Enum
let z = match y {
Option::Some(val) => val + 1,
Option::None => 0,
};
z
}
}