What is Enum in Swift?
In Swift, an enum (short for "enumeration") is a data type that allows you to define a group of related values as a distinct type. Enums are a fundamental construct in Swift and are used to define a finite set of possible values or cases for a particular data type.
In this example, CompassDirection is an enum that represents the four cardinal directions: north, south, east, and west. Each of these directions is a case of the enum.
You can use enums to represent a variety of scenarios, not just simple choices like cardinal directions. Enums are often used to model states, options, and other types of data where you have a fixed set of possibilities.
Here's how you can use an enum in Swift:
In this example, we create an instance of the CompassDirection enum called direction and then use a switch statement to determine the value of direction and perform different actions based on its value.
Enums in Swift can also have associated values and raw values, which provide additional flexibility for representing data. Associated values allow you to attach additional data to enum cases, while raw values associate a predefined value (such as an integer or a string) with each case. Enums are a powerful feature in Swift that makes your code more expressive and type-safe.
enum CompassDirection {
case north
case south
case east
case west
}
In this example, CompassDirection is an enum that represents the four cardinal directions: north, south, east, and west. Each of these directions is a case of the enum.
You can use enums to represent a variety of scenarios, not just simple choices like cardinal directions. Enums are often used to model states, options, and other types of data where you have a fixed set of possibilities.
Here's how you can use an enum in Swift:
let direction = CompassDirection.north
switch direction {
case .north:
print("You are heading north.")
case .south:
print("You are heading south.")
case .east:
print("You are heading east.")
case .west:
print("You are heading west.")
}
In this example, we create an instance of the CompassDirection enum called direction and then use a switch statement to determine the value of direction and perform different actions based on its value.
Enums in Swift can also have associated values and raw values, which provide additional flexibility for representing data. Associated values allow you to attach additional data to enum cases, while raw values associate a predefined value (such as an integer or a string) with each case. Enums are a powerful feature in Swift that makes your code more expressive and type-safe.