Refactoring enums which cases contain the same data
Basics article available: EnumsEnums with associated values are awesome, but if many cases need to include the same data, it’s perhaps time to refactor that enum into a different solution — for example by wrapping it in a struct that contains the shared data.
Here all of our Warning
enum’s cases contains a path
, so to reduce duplication and making handling paths easier, we move it to a wrapping struct instead:
// Before
enum Warning {
case fileUnreadable(path: String)
case decodingFailed(path: String, DecodingError)
case unknownError(path: String, Error)
}
// After
struct Warning {
let path: String
let reason: Reason
}
extension Warning {
enum Reason {
case fileUnreadable
case decodingFailed(DecodingError)
case unknownError(Error)
}
}