Understanding enumerations

Let's say you want to store the following:

  • Compass directions (E, W, N, and S)
  • Traffic light colors
  • The colors of a rainbow

You would use an enumeration for this. You can group together related values in an enumeration.

Let's say you want to program a traffic light. You can use an integer variable to represent different traffic light colors, like this:

// Traffic light variable, 0 is red, 1 is yellow, and 2 is green
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 value1
case value2
case value3
}

Let's look at how to work with enumerations. You'll learn to create and manipulate them. You'll start by creating one to represent a traffic light.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.82.167