Menu
CoddyTech

Enums as Finite Choices

Lesson 12 of 48 in Coddy's Swift for R Developers course.

R factors model categorical data with levels. Their internal integer codes are not the displayed labels or arbitrary business values, so this example converts to the label before looking up a margin. Invalid labels may become missing values, and levels belong to the data object rather than a compiler-declared enum type.

A Swift enum declares a finite set of cases. A variable of that enum type cannot hold an unrelated integer or arbitrary new string. Methods and computed properties can derive behavior from the current case; an exhaustive switch helps expose missing cases when the type changes.

The Swift enum keeps layout choices in the type system and derives a margin with an exhaustive switch. A source factor should not be ported by treating its internal code as a stable domain value. Preserve the meaning of the category and its missing-value policy separately.

Complete R comparison program:

choice <- factor("roomy", levels = c("compact", "roomy"))
margins <- c(compact = 4L, roomy = 12L)
cat(unname(margins[as.character(choice)]), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

Layout.swift

enum Layout {
    case compact, roomy
    var margin: Int {
        switch self {
        case .compact: return 4
        case .roomy: return 12
        }
    }
}

main.swift

let choice: Layout = .roomy
print(choice.margin)
challenge icon

Challenge

Easy

Implement Signal.next() -> Signal and Signal.label: String in Signal.swift. Cases are red, green, amber. The cycle is red to green to amber to red, and label is the lowercase case name. Input is one case name; output the next label.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Signal.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return Signal.red.next() == .green && Signal.green.next().next() == .red && Signal.amber.label == "amber"
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for R Developers

Practice on your own: Swift playground