Enums are generally used for creating custom types with a limited set of values:
-
Create an enum in solidity with the enum keyword:
enum Direction {
// Options
}
-
Enums should contain at least one member:
enum Direction {
North,
East,
South,
West
}
- You can initialize enums directly:
Direction path = Direction.North;
- Enums support explicit conversion to and from all integer types:
function getCurrentChoice() view public
returns (uint) {
return uint(path);
}
- Use the following contract as an example of enums:
pragma solidity ^0.4.23;
contract Navigation {
// enum declaration
enum Direction {
North,
East,
South,
West
}
// Default direction
Direction path = Direction.North;
// Function which accepts enum as input
function changeDirection(Direction dir) public {
path = dir;
}
// Function which returns enum. Since enum is not part of ABI, return type will be changed to uint
function getCurrentDirection() view public
returns (Direction) {
return path;
}
}