Enum explained in-depth with code examples in Swift

An enumeration, or enum, is a user-defined data type in Swift that allows you to define a group of related values. Enums provide a way to represent a finite set of possibilities, making your code more expressive and readable.

Let's dive into the details of enums with some code examples:

Basic Enum

A basic enum defines a set of named values:


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

In this example, we have defined the CompassDirection enum with four possible values: north, south, east, and west.

Associated Values

Enums can also have associated values, allowing you to attach additional information to each case:


enum HTTPResponse {
    case success(Int)
    case failure(Int, String)
}
  

In this example, the HTTPResponse enum has two cases: success and failure. The success case is associated with an integer value, representing the HTTP status code. The failure case is associated with both an integer value and a string value, indicating the status code and the error message, respectively.

Raw Values

An enum can also have raw values, which are pre-defined values of a specific type associated with each case. Raw values can be of any type that conforms to the RawRepresentable protocol:


enum Planet: String {
    case mercury = "Mercury"
    case venus = "Venus"
    case earth = "Earth"
    case mars = "Mars"
}
  

In this example, the Planet enum has raw values of type String. Each case is associated with a string value.

Using Enums

Once you have defined an enum, you can use it in your code:


let direction = CompassDirection.north
print(direction) // Output: north

let response = HTTPResponse.success(200)
switch response {
case .success(let statusCode):
    print("Success with status code: \(statusCode)")
case .failure(let statusCode, let errorMessage):
    print("Failure with status code \(statusCode) and error message: \(errorMessage)")
}

let planet = Planet.earth
print("I live on \(planet.rawValue)")
  

In this example, we create instances of enums and demonstrate various ways to access and use their values.

Conclusion

Enums are a powerful feature in Swift that allow you to define a set of related values and add meaning to your code. Whether you're representing a finite set of options or attaching additional information to each case, enums provide clarity and improve the readability of your code.

Explore more about enums in the official Swift documentation to unlock their full potential in your projects.