Enumerations
Enums, short for enumerations, are a variable type that defines a set of constants that need to be grouped together. Unlike normal constants, where we want to store a certain value, enums automatically assign values to a constant.
In Chapters 2 and 5, we saw that it’s very important to have well-named variables. This way, we always know what they will contain. We can actually do this for the values of variables too, with named values. Using named values, we can associate a human-readable name with a certain value, making code more readable. It also removes magic numbers from the code. Have a look at this enum:
enum DAMAGE_TYPES { NONE, FIRE, ICE }
Here, we create an enum called DAMAGE_TYPES
that defines three named values – NONE
, FIRE
, and ICE
. You can access these values like so:
DAMAGE_TYPES.FIRE
Let’s try printing them out:
print(DAMAGE_TYPES.NONE) print(DAMAGE_TYPES.FIRE) print...