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:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.