Enums let you group related values together. Switch pattern matching helps you check which value the enum holds and run code based on it.
Enum with switch pattern matching in 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.
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 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)") }
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") }
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.
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)
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.
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.
Practice
enum with associated values in Swift?Solution
Step 1: Understand enum basics
An enum groups related values under one type, making code organized.Step 2: Recognize associated values
Enums with associated values can store extra data for each case, like a label or number.Final Answer:
To group related values and store extra data in each case -> Option AQuick Check:
Enum with associated values = group + extra data [OK]
- Confusing enums with classes
- Thinking enums only hold fixed values
- Assuming enums are functions
switch in Swift?Solution
Step 1: Recall switch case syntax for enums
In Swift, to match an enum case with associated values, usecase .caseName(let variable):.Step 2: Identify correct pattern
case .someCase(let value): uses the correct dot syntax and binding withlet.Final Answer:
case .someCase(let value): -> Option AQuick Check:
Switch enum case with let binding = case .someCase(let value): [OK]
- Missing dot before case name
- Using = instead of :
- Wrong arrow or braces syntax
enum Direction {
case north, south, east, west
}
let dir = Direction.east
switch dir {
case .north:
print("Going North")
case .south:
print("Going South")
case .east:
print("Going East")
case .west:
print("Going West")
}Solution
Step 1: Identify enum value assigned
The variablediris assignedDirection.east.Step 2: Match switch case
The switch matches.eastcase and prints "Going East".Final Answer:
Going East -> Option DQuick Check:
dir = east prints "Going East" [OK]
- Confusing enum case names
- Forgetting to include all cases
- Assuming default case runs
enum Result {
case success(Int)
case failure(String)
}
let res = Result.success(10)
switch res {
case .success(let value):
print("Value: \(value)")
case failure(let message):
print("Error: \(message)")
}Solution
Step 1: Check switch case syntax
In switch, enum cases must be prefixed with a dot, like.failure.Step 2: Identify missing dot
The second case usesfailurewithout a dot, causing a syntax error.Final Answer:
Missing dot before 'failure' in switch case -> Option CQuick Check:
Enum case in switch needs dot prefix [OK]
- Omitting dot before enum case in switch
- Confusing associated value types
- Forgetting to handle all cases
describeShape(.rectangle(width: 5, height: 10)) print?enum Shape {
case circle(radius: Double)
case rectangle(width: Double, height: Double)
case point
}
func describeShape(_ shape: Shape) {
switch shape {
case .circle(let r):
print("Circle with radius \(r)")
case .rectangle(let w, let h):
print("Rectangle \(w) x \(h)")
case .point:
print("Just a point")
}
}Solution
Step 1: Identify enum case and associated values
The input is.rectangle(width: 5, height: 10), so width = 5 and height = 10.Step 2: Match switch case and print
The switch matches.rectangle(let w, let h)and prints "Rectangle 5.0 x 10.0".Final Answer:
Rectangle 5.0 x 10.0 -> Option BQuick Check:
Rectangle case prints dimensions [OK]
- Using wrong variable names in case
- Missing multiple associated values in pattern
- Assuming default case runs
Ready to prove it?
Pass the test and this pattern moves unknown
