0
0
Swiftprogramming~5 mins

Enum with switch pattern matching in Swift

Choose your learning style9 modes available
Introduction

Enums let you group related values together. Switch pattern matching helps you check which value the enum holds and run code based on it.

You want to represent a fixed set of options, like days of the week or directions.
You need to run different code depending on the enum's current value.
You want clear and safe handling of different cases without errors.
You want to extract associated data from enum cases easily.
You want your code to be easy to read and maintain.
Syntax
Swift
enum EnumName {
    case case1
    case case2(AssociatedType)
    case case3
}

let value = EnumName.case1

switch value {
case .case1:
    // code for case1
case .case2(let data):
    // code using data
case .case3:
    // code for case3
}

Use case .caseName inside switch to match enum cases.

Use let to get associated values from enum cases.

Examples
Simple enum with no associated values. Switch matches each direction.
Swift
enum Direction {
    case north
    case south
    case east
    case west
}

let travelDirection = Direction.north

switch travelDirection {
case .north:
    print("Going north")
case .south:
    print("Going south")
case .east:
    print("Going east")
case .west:
    print("Going west")
}
Enum with associated values. Switch extracts the data inside each case.
Swift
enum Result {
    case success(String)
    case failure(Int)
}

let operationResult = Result.success("File saved")

switch operationResult {
case .success(let message):
    print("Success: \(message)")
case .failure(let errorCode):
    print("Error code: \(errorCode)")
}
Another simple enum example showing clear switch cases.
Swift
enum Light {
    case red
    case yellow
    case green
}

let trafficLight = Light.red

switch trafficLight {
case .red:
    print("Stop")
case .yellow:
    print("Get ready")
case .green:
    print("Go")
}
Sample Program

This program defines a Weather enum with three cases. Some cases have extra data. The describe function uses switch pattern matching to print messages based on the weather. It shows how to handle each case clearly.

Swift
import Foundation

enum Weather {
    case sunny
    case rainy(Int)  // Int is mm of rain
    case windy(Double) // Double is wind speed
}

func describe(weather: Weather) {
    switch weather {
    case .sunny:
        print("It's a bright sunny day!")
    case .rainy(let mm):
        print("It's raining with \(mm) mm of rain.")
    case .windy(let speed):
        print("It's windy with speed \(speed) km/h.")
    }
}

let todayWeather = Weather.rainy(20)
print("Before switch:", todayWeather)
describe(weather: todayWeather)

let tomorrowWeather = Weather.sunny
print("Before switch:", tomorrowWeather)
describe(weather: tomorrowWeather)
OutputSuccess
Important Notes

Switch pattern matching on enums runs in constant time O(1).

Space used depends on enum size but is usually small.

Common mistake: forgetting to handle all enum cases in switch, which causes a compile error.

Use switch pattern matching when you want clear, safe, and readable code for enum values.

Summary

Enums group related values and can hold extra data.

Switch pattern matching checks enum cases and extracts data.

This makes your code safe and easy to understand.