Understanding enumerations
Let's say you want to store the following:
- Compass directions (
E
,W
,N
, andS
) - Traffic light colors
- The colors of a rainbow
You would use an enumeration for this, which allows you to group related values together. To understand why enumerations would be ideal for this purpose, let's consider the following example.
Imagine you're programming a traffic light. You can use an integer variable to represent different traffic light colors, where 0
is red, 1
is yellow, and 2
is green, like this:
var trafficLight = 2
Although this is a possible way to represent a traffic light, what happens when you assign 3
to trafficLight
? This will cause problems as 3
does not represent a valid traffic light color. So, it would be better if we could limit the possible values of trafficLight
to the colors it can display.
Here's what an enumeration declaration looks like:
enum EnumName { case...