0
0
Swiftprogramming~5 mins

Why enums are powerful in Swift

Choose your learning style9 modes available
Introduction

Enums in Swift help group related values together in a clear way. They make your code safer and easier to understand.

When you have a fixed set of related options, like days of the week or directions.
When you want to handle different cases with specific code for each.
When you want to make your code safer by avoiding invalid values.
When you want to attach extra information to each case.
When you want to use pattern matching to write clean and clear code.
Syntax
Swift
enum EnumName {
    case option1
    case option2
    case option3
}

Each case represents a possible value of the enum.

You can add extra data to cases using associated values.

Examples
Simple enum listing four directions.
Swift
enum Direction {
    case north
    case south
    case east
    case west
}
Enum with associated values to store extra data for each case.
Swift
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}
Enum used to represent success or failure with extra info.
Swift
enum Result {
    case success(String)
    case failure(Error)
}
Sample Program

This program uses an enum to represent traffic light colors. It returns an action for each color using a switch statement.

Swift
enum TrafficLight {
    case red
    case yellow
    case green
}

func action(for light: TrafficLight) -> String {
    switch light {
    case .red:
        return "Stop"
    case .yellow:
        return "Get Ready"
    case .green:
        return "Go"
    }
}

let currentLight = TrafficLight.yellow
print(action(for: currentLight))
OutputSuccess
Important Notes

Enums improve code safety by limiting possible values.

Using switch with enums helps handle all cases explicitly.

Associated values let you store extra info with each case.

Summary

Enums group related values clearly and safely.

They help avoid invalid values and bugs.

Enums with associated values add flexibility.