Creating an enumeration

Let's create an enumeration to represent a traffic light. Perform the following steps:

  1. Type the following code as shown into your playground and run it:
// Enumerations// Traffic light enumerationenum TrafficLight {    case red    case yellow    case green}var trafficLight = TrafficLight.red

This creates an enumeration named TrafficLight, which groups together the red, yellow, and green values. As you can see, now the value for trafficLight is limited to red, yellow, and green; if you were to try to set the values as anything else, an error will be generated.

Enumerations can contain methods. Let's add a method to trafficLight. This method will return a string representing the trafficLight color.

  1. Modify your code as shown ...

Get iOS 13 Programming for Beginners - Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.