2

I have an enum with certain predefined data. If at a later date, I have to add or push in more choices , can I edit the enum using some function ?

enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }

If I need to add a choice, GoBack , can I do that ?

Thanks

Ashish kumar
  • 334
  • 1
  • 3
  • 11

2 Answers2

1

Enums are constants so you can't.

Regardless of programming language, constants are evaluated compile time and cannot be changed run time.

Mikko Ohtamaa
  • 22,269
  • 6
  • 62
  • 127
1

As Mikko says, the short answer is "no."

To make the list dynamic, you would have to use storage and implement functions to add, update, delete options. This will increase the gas cost at runtime because it would be reading from storage instead of reading values compiled into the bytecode at compile time. You would probably also want access control on the maintenance functions, e.g. onlyOwner.

You can find some "set types" over here: https://github.com/rob-Hitchens/SetTypes

These are implementations of the Mapped Structs with Delete-enabled Index described over here: Are there well-solved and simple storage patterns for Solidity?

You might end up with an implementation that looks something like this:

contract Normalized {

using Bytes32Set for Bytes32Set.Set;

Bytes32Set choices;

function doSomething(bytes32 choice) public { require(choices.exists(choice), "invalid choice"); // carry on }

function newChoice(bytes32 choice) public { choices.insert(choice); // does not permit duplicates }

function remChoice(bytes32 choice) public { choices.remove(choice); // requires choice to remove does indeed exist }

function choiceCount() public returns(uint) { return choices.count(); }

function getChoice(uint index) public returns(bytes32) { return choices.keyAtIndex(index); }

}

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145