In Solidity, Enums stand for Enumerable. Enums are user-defined data types that restrict the variable to having only one of the predefined values.
The predefined values present in the enumerated list are called enums. Internally, enums are treated as numbers. Solidity automatically converts the enums to unsigned integers. An enum should have at least one value in the enumerated list. This value cannot be a number (positive or negative) or a boolean value (true or false).
Enums limit the number of possible values for a variable to a small number of predefined options. The values contained within this enumerated list are referred to as enums. It is possible to limit the number of bugs in your code by making use of enums in your code.
As an example, if we were to investigate an application for a fresh juice shop, it would be possible to limit the glass size to three options: small, medium, and big. This would ensure that no one would be able to order a size other than small, medium, or large because of the restriction.
Enum examples:
pragma solidity ^0.5.0;
contract test {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize choice;
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;
function setLarge() public {
choice = FreshJuiceSize.LARGE;
}
function getChoice() public view returns (FreshJuiceSize) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Enum {
// Enum representing shipping status
enum Status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}
// Default value is the first element listed in
// definition of the type, in this case "Pending"
Status public status;
// Returns uint
// Pending - 0
// Shipped - 1
// Accepted - 2
// Rejected - 3
// Canceled - 4
function get() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
// You can update to a specific enum like this
function cancel() public {
status = Status.Canceled;
}
// delete resets the enum to its first value, 0
function reset() public {
delete status;
}
}
For more content, follow me on - https://linktr.ee/shlokkumar2303
Top comments (0)