Understanding enums

An enum is a type that holds a finite set of predefined values. Enums are often used to represent a particular state or result of an operation. The best way to learn what this means is to look at an example of an enum that represents the state of a traffic light:

struct TrafficLight {
  var state: TrafficLightState
  // ...
}

enum TrafficLightState {
  case green, yellow, red
}

This sample shows a TrafficLight struct that has a state property. The type of this property is TrafficLightState, which is an enum. The TrafficLightState defines three possible states for a traffic light. This is very convenient because an enum such as this eliminates the possibility of a bad state because the compiler can now enforce that you never end up with an invalid value.

Enums can also contain properties and methods, just like structs can. However, an enum can also have an associated value. This means that each possible case can have a representation in a different type, such as a String. If you modify TrafficLightState as shown here, it will have a String as its rawValue:

enum TrafficLightState: String {
  case green, yellow, red
}

If Swift can infer the raw value, you don't have to do anything more than add the type of the raw value to the enum's type declaration. In this sample, the raw value for the green enum case will be the "green" string. This can be convenient if you need to map your enum to a different type, for instance, to set it as a label's text.

Just like structs, enums cannot inherit functionality from other objects, but they can conform to protocols. You make an enum conform to a protocol with an extension, just like you would do for classes and structs.

This wraps up the exploration of value types. Now that you know what value types and reference types are, let's explore some of their differences!

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

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