Blog / July 26, 2023 / 2 mins read / By Mahi Garg

Swift Enum in detail

Enumerations, commonly known as enums, are a versatile feature in Swift that allow you to define a group of related values in a structured manner. Enums provide a way to define a type with a limited set of related values. They help make code more readable, self-documenting, and type-safe by enforcing specific cases.

Basic Enum Definition:

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

let direction: CompassDirection = .north

Enum with Associated Values:

Enums can also hold associated values, allowing them to represent more complex data structures.

enum Result<T, E> {
    case success(T)
    case failure(E)
}

let successResult: Result<Int, String> = .success(42)
let failureResult: Result<Int, String> = .failure("Error: Data not found")

Raw Value Enumerations:

Enums can have raw values assigned to each case, making them particularly useful when working with data that needs to be serialized or compared.

enum Weekday: Int {
    case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}

let today: Weekday = .wednesday
print("Today is \(today.rawValue)") // Output: Today is 4

Associated Values and Methods:

Enums can have methods associated with them, enabling behavior specific to each case.

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    
    func area() -> Double {
        switch self {
        case .circle(let radius):
            return Double.pi * radius * radius
        case .rectangle(let width, let height):
            return width * height
        }
    }
}

let circleShape = Shape.circle(radius: 5.0)
let rectangleShape = Shape.rectangle(width: 4.0, height: 3.0)

print("Circle Area: \(circleShape.area())") // Output: Circle Area: 78.53981633974483
print("Rectangle Area: \(rectangleShape.area())") // Output: Rectangle Area: 12.0

Enum Iteration:

Enums can be iterated, making them useful for generating a list of cases.

enum Fruit: CaseIterable {
    case apple, orange, banana, grape
}

for fruit in Fruit.allCases {
    print(fruit)
}

Conclusion:

Swift enums provide a structured and type-safe way to define a group of related values. Whether you need to represent simple cases, associate values with them, or even assign raw values, enums offer a powerful mechanism to enhance code readability and maintainability. By understanding the concepts and examples covered in this article, you’ll be better equipped to utilize enums effectively in your Swift programming projects.

Comments