Swift Enumerations
In Swift, an Enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. Enumeration is a user-defined data type that consists of a set of named values, called members or cases.
Declaring an Enumeration
To declare an enumeration, you use the enum
keyword followed by the name of the enumeration. Here's a simple example:
1enum Direction { 2 case north 3 case south 4 case east 5 case west 6}
In the above example, we declared an enumeration called Direction
which contains four possible cases - north, south, east and west.
We can also declare an enumeration with all the cases in a single line separated by a comma:
1enum Day: String { 2 case monday, tuesday, wednesday, thursday, friday, saturday, sunday 3}
In the above example, we declared an enumeration called Day
which contains seven possible cases - monday, tuesday, wednesday, thursday, friday, saturday, and sunday.
We can also associate values with enumeration cases:
1enum Planet: Int { 2 case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune 3}
In the above example, we declared an enumeration called Planet
which contains eight possible cases, and we associated a raw value of type Int
with each case.
Accessing Enumeration Values
You can access an enumeration value using the dot syntax. Here's an example:
1var dir = Direction.north 2dir = .south
In the above example, we assigned the Direction.north
value to the dir
variable, and then we assigned the Direction.south
value to it.
We can also access the raw value of an enumeration case:
1let planet = Planet.jupiter 2print(planet.rawValue) // Output: 5
In the above example, we accessed the jupiter
case of the Planet
enumeration and printed its associated raw value, which is 5
.
Switch Statements with Enumerations
Swift switch statements are very useful when working with enumerations. Here's an example:
1enum TrafficLight { 2 case red, yellow, green 3} 4 5var light = TrafficLight.red 6 7switch light { 8case .red: 9 print("Stop!") 10case .yellow: 11 print("Prepare to stop.") 12case .green: 13 print("Go!") 14}
In the above example, we declared an enumeration called TrafficLight
with three cases - red, yellow, and green. We then assigned the TrafficLight.red
value to the light
variable and used a switch statement to determine what action to take based on the value of the light
variable.
Iterating over Enumerations
You can also iterate over an enumeration to access its cases. Here's an example:
1enum Beverages: CaseIterable { 2 case coke, pepsi, fanta, sprite 3} 4 5for beverage in Beverages.allCases { 6 print(beverage) 7}
In the above example, we declared an enumeration called Beverages
with four cases - coke, pepsi, fanta, and sprite. We then used the allCases
property to iterate over the enumeration and print each case.