In Sway, the Option type is a commonly used pattern matching type that represents a value that may be present (Some) or absent (None).
In the provided code, we define a smart contract named MyContract
with a function called test_func
that returns a tuple containing three Option types, each containing a boolean value.
test_func
function, we create three Option types: liked
with a value of Some(true); disliked
with a value of Some(false); and none
with a value of None.The test_func
function of this smart contract ultimately returns a tuple containing three Option types. This simple example is intended to show you how to use Option types in Sway to represent values that may exist. We hope this tutorial helps you better understand Option types in Sway.
contract; // Result= Ok(T) | Err(E) enum MathError { DivByZero: (), } fn div(x: u64, y: u64) -> Result { if y == 0 { return Result::Err(MathError::DivByZero); } Result::Ok(x / y) } abi MyContract { fn test_div(x: u64, y: u64) -> u64; } impl MyContract for Contract { fn test_div(x: u64, y: u64) -> u64 { let res = div(x, y); match res { Result::Ok(val) => val, Result::Err(err) => revert(0), } } }