What is an Enum?
The word Enum stands for Enumerable. These are value types that consist of a predefined list of constant values. The values in the enumerated list are called enums and they remain constants. In solidity, enums are the only way to create a user-defined type.
Enums Use Cases
Optional/nullable data type
Flag with extra information needed in some cases -Variant data types
Modeling states in a state machine where each stale can have some data associated with it. -List of operators for batching processing where each operation can have its own argument
Alternative function overloading that makes avoiding combinatorial explosion when there are multiple parameters that need variants
Nested data structures with heterogeneous nodes.
What can’t be done with Enums
Implicit conversations
Adding numbers or booleans as members of the enums
Using Enums as key type mapping
Defining enums in solidity with a compiler version lower than 0.5.0
Enums cannot be declared within functions
Plain Enum:
Enum Alphabets{A, B, C}
Declaring An Enum
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
contract EnumExample {
// creates an enum
Enum Zipper{Up, Down}
//Declares the variable of the type Zipper
Zipper public zipper;
// First Function to take up zipper
function zipperUp() public {
zipper = Zipper.Up;
}
// Second Function to bring down zipper
function zipperDown() public {
zipper = Zipper.Down;
}
//Function to get the value of zipper;
function getZipperState() public view returns(Zipper){
return zipper;
}
}