Understanding Enums in Solidity.

In Solidity, Enums are a way of creating user-defined types. They are used to restrict a variable to have one of the only pre-defined values. Enums is the short form for enumerated, and the values that are in the enumerated list, are called enums.

They basically allow you to represent optional data. For example, you can have a different color (red, blue, white) of a car. This color list which in this case is an enum list represents the different states that the car object can be seen as.

You write an enum in Solidity by first declaring the "Enum" keyword before the name of the enum. Let us create an enum with the name FANSTATE, that has two values, ON and OFF, to show if the fan is ON or OFF. N.B Solidity knows how to convert an integer to an enum. if an integer is passed to a function that reads the enum, solidity is able to convert that integer to the enum representing the integer. In our example, 0 will be converted to the ON value in the enum list. This was explained with an example below. Let us create an enum in solidity. enum.PNG

  • we start writing the enum by using the enum keyword, then we give the enum a name. By convention, the name and the options on the enum list are written in capital letters.

  • After this, we create a variable with the state of our Enum. We can then manipulate this enum as we choose. For example to be able to manipulate the enum, let us create a function that modifies the enum.

enum2.PNG

In this function, the name of the function is declared, and then the state of the enum can be assigned to any of the values in the enum list. You can also use the declared enum like in the example below.

enum3.PNG

Finally, let us see how we can accept an enum as an argument. We'll create a function that accepts an enum as an argument.

enum4.PNG

  • First, we declare the enum type and then the name of the enum.

  • From outside the smart contract, it is not directly possible to pass in an enum as an argument, instead, you pass in an integer. If you pass in 0, it is going to be converted to the first value in the enum list, if you pass in 1, it would be converted to the second value, and so on.