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.

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