Quick Answer
Enums with associated values and methods
Understanding the Issue
Swift enums are much more powerful than in other languages. They can have associated values, methods, and conform to protocols. They're ideal for state modeling.
The Problem
This code demonstrates the issue:
Swift
Error
// Problem: Basic enum
enum Direction {
case north, south, east, west
}
The Solution
Here's the corrected code:
Swift
Fixed
// Solution: Advanced enum
enum Result {
case success(data: Data)
case failure(error: Error)
func analyze() {
switch self {
case .success(let data):
process(data)
case .failure(let error):
handle(error)
}
}
}
Key Takeaways
Use enums to model finite states with associated data.