envoy_

Vedant Chainani

Posted on June 9, 2022

Day 12 - Enums

GitHub logo 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
} 
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

When we run the getDefaultDay function, we get the default value of the enumerator.

0:uint8: 0
Enter fullscreen mode Exit fullscreen mode

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.


💖 💪 🙅 🚩
envoy_
Vedant Chainani

Posted on June 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 30 - Polymorphism
100daysofcode Day 30 - Polymorphism

August 3, 2022

Day 28 - Abstract Contract and Interface
100daysofcode Day 28 - Abstract Contract and Interface

July 31, 2022

Day 27 - Libraries
100daysofcode Day 27 - Libraries

July 30, 2022

Day 26 - Events and Hashing
100daysofcode Day 26 - Events and Hashing

July 29, 2022

Day 25 - Fallback and receive Functions
100daysofcode Day 25 - Fallback and receive Functions

June 22, 2022