Enumeration also Enum contains predefined constants or fixed values. It is also similar to Enum in another programming language.

Nim Enum examples

Enum declared with simple values or with its values

Let’s declare a simple Enum

type
  WEEKEND = enum
    SUNDAY, SATURDAY

By default, Enum values are ordered and assigned with values 0,1. The above declaration is an implicit order

ord(SUNDAY) or ord(WEEKEND.SUNDAY)=0 ord(SATURDAY) or ord(WEEKEND.SATURDAY)=1

echo ord(WEEKEND.SUNDAY)
echo ord(WEEKEND.SATURDAY)

Let’s declare explicit Enum

type
  WEEKEND = enum
    SUNDAY=1,SATURDAY=2

You can also define and declare Enums

type
  WEEKEND = enum
    SUNDAY = (1, "Sunday"),
    SATURDAY = (2, "Saturday"),

Enum can also be declared with pure pragma and all attributes are added without ENUM type

for non-ambiguous references.

Below example

  • FRIDAY only exists WEEKEND type and non-ambiguous reference, These can be accessed without Type. WEEKEND.FRIDAY and FRIDAY both return FRIDAY
  • SUNDAY, SATURDAY exists in both WEEKEND and WEEKEND1 and values are ambiguous. These can be accessed with WEEKEND.SUNDAY and WEEKEND.SATURDAY. and SUNDAY and SATURDAY return an error.

\## Declare Enum type
type
  WEEKEND {.pure.} = enum
    SUNDAY, SATURDAY, FRIDAY
type
  WEEKEND1 {.pure.} = enum
    SUNDAY, SATURDAY

echo FRIDAY # FRIDAY
echo WEEKEND.SUNDAY # SUNDAY
echo SATURDAY # Error: ambiguous identifier: 'SATURDAY'

Enum iteration in NIM

NIM provides different ordinal functions.

low and high and lowest and highest value of an enum ord gives the ordinal value of an enum constant.

use the for in loop to iterate lowest to highest and print the enum and ordinal value

## Declare Enum type
type
  WEEKEND {.pure.} = enum
    SUNDAY, SATURDAY
for value in ord(low(WEEKEND))..
                 ord(high(WEEKEND)):
  echo WEEKEND(value), " : - : ", value

Output:

SUNDAY : - : 0
SATURDAY : - : 1