In Sway, the Result type is a commonly used pattern matching type that represents the outcome of an operation as either successful (Ok) or unsuccessful (Err).
In the provided code, we define a smart contract named MyContract with a function called test_div that accepts two u64 type parameters and returns a u64 type value.
MathError enum to represent possible errors in mathematical operations.div function, we check if the divisor is zero, and if so, we return a result with MathError::DivByZero as the error.test_div function, we call the div function and use pattern matching to handle the result. If the result is successful, we return the value; if the result is an error, we revert the transaction.The test_div function of this smart contract ultimately returns a u64 type value. This simple example is intended to show you how to use Result types in Sway to handle potential errors. We hope this tutorial helps you better understand Result types in Sway.
contract;
// if, else if, else
// if let
abi MyContract {
fn test_func(x: u64) -> u64;
}
impl MyContract for Contract {
fn test_func(x: u64) -> u64 {
// if, else if, else
if x < 10 {
// do something
} else if x < 20 {
// do something else
} else {
// do something else
}
// if let
let mut y = 0;
if x < 10 {
y = x * x;
} else {
y = x + 1;
}
// Assign the outcome of if statements to the variable y
let y = if x < 10 {
// do something, for example
x * x
} else {
// do something else, for example
x + 1
}; // Notice semicolon here
y
}
}