Solidity Validations – Checking for Valid Enum Values in Solidity

solidity

With the following enum definition in Solidity code…

enum Direction { North, South, East, West }

… I would like to set up a for-loop that iterates over this enum's values, e.g.

for (uint8 dirn = 0; dirn < xxx; dirn++) { ... }

Is there a way for the code to check what the size of the enum is, i.e. what should replace xxx, other than the hard-coded literal value 4?

Best Answer

Possibly here is what you can do.

  1. Declare array to store the enum choices
  2. In constructor call push all the enum choices in the array
  3. In the method to match the enum choice just loop the array and match it against the passed enum choice
Related Topic