Enum Data Type in Solidity

The enum data type in Solidity restricts a variable to have only predefined values. It is in a way similar to the boolean data type, that allows values to be either True or False. But the allowed values in a enum can be defined by the blockchain developer. The enum data type can help to reduce bugs and makes the code more robust. It makes the code also easier to read and understand.

To declare a enum data type, the enum keyword is used. Enums require at least one value and cannot have more than 256 values. They can be declared inside a contract or function but also on the file level outside of contracts. Let's declare a enum that allows only specific Tokens to be selected.

enum Token 

The enum Token can only have the predefined values ETH, LINK and SOL. To store the token in a public state variable define it like this:

Token public token;

The default value of the enum will be the first element in the definition of the enum, in our example ETH. To change the value we can update the toke variable and give it a new value:

token = Token.LINK;

Another possible use case of enums, that demonstrate its advantages, is to define weekdays:

enum day_of_week