Explain Enum in Swift

Enum is also known as Swift Enumeration. Enum is a data type which contains a set of the related values. It is declared in a class and its values are accessed through the instance members of that class.

In Swift, an enum, short for enumeration, is a user-defined data type that enables you to define a group of related values. Enums in Swift are powerful constructs that allow you to represent a fixed set of options or states within your code. They help make your code more readable, maintainable, and less error-prone by providing a way to work with predefined, named values.

Here’s how you define an enum in Swift:

enum CompassDirection {
case north
case south
case east
case west
}

In this example, CompassDirection is the name of the enum, and it defines four cases: north, south, east, and west. Each case represents a distinct value that an instance of the CompassDirection enum can hold.

Enums can also have associated values and raw values:

  1. Associated Values: You can attach additional data to enum cases. For instance, if you want to represent a traffic light, you might have associated values representing the colors:
enum TrafficLight {
case red
case yellow
case green(duration: TimeInterval)
}
let light = TrafficLight.green(duration: 30.0)

  1. Raw Values: Enums can be assigned default values, known as raw values. These values must all be of the same type and are assigned automatically if not provided explicitly:
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

In this case, Planet.mercury has a raw value of 1, Planet.venus has a raw value of 2, and so on.

Enums in Swift are versatile and can be used in various scenarios, including representing states, options, error conditions, and more. They provide a concise and expressive way to define a set of related values, making your code easier to understand and maintain.