Grant Emerson

Indirect Cases

Indirect Cases — SwiftMoji Entry #6

In Swift, enumerations (or enums for short) are data structures that define a group of related values called cases. Although not required, each case in an enum can either provide a raw value (with “=”) or associated value (with “()”). The latter is interesting because it adds a layer of customizability and depth to a case. For example, an error enum might have a String as the associated value for its cases in order to handle corresponding descriptions. Additionally, with the indirect keyword, an enum’s cases can have recursive associated values that are of the same type as the enclosing enum. In the following code example, there is a Folder enum with two cases, one for subfolders and the other for documents. In the subfolder case, the associated value is a tuple containing its name and an Array of Folders it contains. The fact that a Folder can contain Folders creates a recursive relationship and therefore, requires the indirect keyword.

indirect enum Folder {
    case 📁(label: String, contents: [Folder])
    case 📄(String)
}

let models = Folder.📁(label: "Models", contents: [.📄("Experience.swift")])
let views = Folder.📁(label: "Views", contents: [.📄("MapperView.swift")])
let controllers = Folder.📁(label: "Controllers", contents: [.📄("MainViewController.swift")])
let xcodeProject = Folder.📁(label: "Business App", contents: [models, views, controllers])
Tagged with: