Understanding Enums
Enums, or enumerations, are a way to define a set of related values in Swift.
Think of an enum like a box that has a bunch of labeled compartments inside of it. Each compartment has a specific label, and it can hold one specific value. You can use the labels to identify the compartments and the values that they contain.
In the same way, an enum in Swift is a collection of related values that are each given a specific name (or label). You can use the names to identify the values and to access the values that they contain.
Here's a simple example of an enum in Swift:
enum Color {
case red
case orange
case yellow
case green
case blue
case indigo
case violet
}
In this example, the Color
enum defines a set of related values that represent the colors of the rainbow. Each value is given a specific name, and the names are used to identify the values and access the values that they contain.
You can use the Color
enum like this:
let primaryColor = Color.red
let secondaryColor = Color.blue
In this example, the primaryColor
and secondaryColor
constants are assigned the values of the Color.red
and Color.blue
cases, respectively. Because the Color
enum defines a fixed set of values, you can only assign values from the Color
enum to variables or constants that are declared as the Color
type.
Enums are a powerful and flexible feature of the Swift programming.