Day 12 - Enums
Vedant Chainani
Posted on June 9, 2022
Envoy-VC / 30-Days-of-Solidity
30 Days of Solidity step-by-step guide to learn Smart Contract Development.
This is Day 12
of 30
in Solidity Series
Today I Learned About Enums in Solidity.
Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading.
Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code.
Syntax
enum <enumerator_name> {
element 1,
element 2,
....,
element n
}
Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract EnumType {
// Creating an enumerator
enum Days {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
// Declaring variables of type enumerator
Days day;
// Setting a default value
Days constant defaultDay = Days.Monday;
// Get default Day
function getDefaultDay() public pure returns (Days) {
return defaultDay;
}
// Set day to a object from the enumerator Days
function setDay() public {
day = Days.Tuesday;
}
// get value of day
function getDay() public view returns (Days) {
return day;
}
}
Output:
When we run the getDefaultDay function, we get the default value of the enumerator.
0:uint8: 0
When we run the getDay function we get 0:uint8: 0
as we have set it to a default value of Monday.
When we run the setDay function and then run the getDay function we get 0:uint8: 1
as setDay function has set the value of day
to Tuesday.
Posted on June 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.