In Solidity, an enum
is a user-defined data type that consists of a set of named values. Enums are a way to create a custom type with a finite set of possible values, which can make your code more readable and less error-prone.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract EnumExample {
// Define an enum with possible states
enum State { Waiting, Active, Completed }
// State variable to store the current state
State public state;
// Set the initial state to 'Waiting'
constructor() {
state = State.Waiting;
}
// Function to set the state to 'Active'
function activate() public {
state = State.Active;
}
// Function to set the state to 'Completed'
function complete() public {
state = State.Completed;
}
// Function to check if the state is 'Completed'
function isCompleted() public view returns (bool) {
return state == State.Completed;
}
}
The enum
named State
is declared with three possible values: Waiting
, Active
, and Completed
.
Enum values are zero-indexed, meaning State.Waiting
is 0
, State.Active
is 1
, and State.Completed
is 2
. You can directly use these values in comparisons and assignments.