Understanding enumerations
Enumerations allow you to group related values together, for example:
- Compass directions (E, W, N, and S)
- Traffic light colors
- The colors of a rainbow
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 trafficLightColor = 2
Although this is a possible way to represent a traffic light, what happens when you assign 3
to trafficLightColor
? This will cause problems as 3
does not represent a valid traffic light color. So, it would be better if you could limit the possible values of trafficLightColor
to the colors it can display.
Here's what an enumeration declaration looks like:
enum EnumName { case value1 case value2 case value3...