In Sway, enums are a data type used to define a set of named constant values. They are a core component of the data type system and can be used to represent different states or choices.
In the provided code, we define a smart contract named MyContract
with a function called test_func
that returns a value of the Error
enum type.
Color
with three enum values: Red
, Blue
, and Green
.Shape
with two enum values: Circle
and Triangle
. The Circle
enum value contains a Point
struct instance and a u64
type value, while the Triangle
enum value contains an array of three Point
struct instances.Error
with two enum values: Auth
and Transfer
. The Auth
enum value contains an AuthError
enum value, and the Transfer
enum value contains a TransferError
enum value.AuthError
with two enum values: NotOwner
and NotApproved
.TransferError
with two enum values: TransferToZeroAddress
and InsufficientBalance
.test_func
function of the smart contract demonstrates how to use these enums. It first defines a Color
enum value, then a Shape
enum value. Finally, it defines an Error
enum value containing an AuthError
enum value.The test_func
function of this smart contract ultimately returns an instance of the Error
enum value. This simple example is intended to show you how to use enums in Sway to define and select different states or options. We hope this tutorial helps you better understand enums in Sway.
contract; // Constants // 0x0000000000000000000000000000000000000000000000000000000000000000 const ZERO_B256: b256 = b256::min(); const ZERO_ADDRESS = Address::from(ZERO_B256); // Associated constants struct Point { x: u64, y: u64, } impl Point { const ZERO: Point = Point { x: 0, y: 0 }; } abi MyContract { fn test_func() -> Point; } impl MyContract for Contract { fn test_func() -> Point { // Can also define a constant inside a function const MY_NUM: u64 = 123; Point::ZERO } }