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])
    }
}

Support Swift by Sundell by checking out this sponsor:

Genius Scan SDK

Genius Scan SDK: Add a powerful document scanner to any iOS app. Genius Scan’s SDK features advanced image processing that’s the result of over 10 years of research and development and can be fully customized and integrated into your app with just one line of code. Mention Swift by Sundell when requesting a free demo to get a 20% discount on your license for a whole year.