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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.