Enums in Solidity
Name the phases; walk them in order with a cast.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// An enum names the phases; the contract walks them in order.
contract SeasonTracker {
enum Season { Dormant, Blossom, Growing, Harvest }
Season public season = Season.Dormant;
function advance() external {
require(season != Season.Harvest, "season over");
season = Season(uint8(season) + 1);
}
function isPicking() external view returns (bool) {
return season == Season.Harvest;
}
}
How it works
enum Seasondefines four ordered constants.Season(uint8(season) + 1)steps to the next phase.requirerefuses to advance past the last.
Keywords and builtins used here
boolcontractenumexternalfunctionpublicrequirereturnreturnsuint8
The run, in numbers
- Lines
- 18
- Characters to type
- 445
- Tokens
- 80
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 80 seconds.
Step 3 of 3 in Storage, step 7 of 28 in Language basics.