Articles, podcasts and news about Swift development, by John Sundell.

Refactoring enums which cases contain the same data

Published on 19 Apr 2019
Basics article available: Enums

Enums 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)

Support Swift by Sundell by checking out this sponsor:


Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.