Articles and podcasts about Swift development, by John Sundell.

Genius Scan SDK

Presented by the Genius Scan SDK

This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.

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)
    }
}
Genius Scan SDK

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.