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

Recursive enums with “fake” cases

Published on 06 Mar 2019
Basics article available: Enums

Indirect enums can provide a great way to set up recursive data structures with a finite number of cases, and static functions can let us define “fake” cases that look like normal cases, but don’t require additional handling in switches:

// Indirect enums are able to reference themselves, enabling
// us to set up recursive data structures.
indirect enum Content {
    case values(Values)
    case script(Script)
    case collection([Content])
}

extension Content {
    // Using static functions, we can create "fake" enum cases,
    // that can act as convenience APIs — without having to add
    // additional case handling code in our switch statements.
    static func text(_ text: String) -> Content {
        return .values(["content": text])
    }
}