Enums in Solidity provide a way to create user-defined types with a finite set of constant values. They are particularly useful when you need to represent a fixed number of options or states within your smart contract.
To define an enum in Solidity, use the enum
keyword followed by the enum name and a list of possible values:
enum Status {
Pending,
Approved,
Rejected
}
In this example, we've defined an enum called Status
with three possible values: Pending
, Approved
, and Rejected
.
Once defined, enums can be used as a type for variables, function parameters, or return values. Here's an example of how to use the Status
enum in a contract:
contract Application {
Status public currentStatus;
constructor() {
currentStatus = Status.Pending;
}
function approve() public {
currentStatus = Status.Approved;
}
function reject() public {
currentStatus = Status.Rejected;
}
}
In this contract, we've used the Status
enum to represent the current status of an application. The contract initializes the status as Pending
and provides functions to update it.
Solidity automatically assigns integer values to enum members, starting from 0. You can access these values or convert between enums and integers:
Status.Pending; // 0
Status.Approved; // 1
Status.Rejected; // 2
Status(1); // Status.Approved
uint(Status.Rejected); // 2
This feature allows for easy comparison and storage of enum values as integers when needed.
Enums are a powerful tool in Solidity for representing a fixed set of options. They enhance code readability and provide type safety, making them an essential feature for smart contract developers to master.
Enums can be effectively combined with other Solidity features like Solidity Structs and Solidity Mappings to create more complex and organized data structures in your smart contracts.
For optimal performance and Solidity Gas Optimization, consider using enums instead of strings when representing a fixed set of options in your contract logic.