Menu
CoddyTech

Enums as Finite Choices

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

Luau string singleton unions can describe a finite set of allowed strings to the type checker. Format is an erased type alias: its values are still ordinary strings at runtime. A dynamic or unchecked boundary therefore needs its own validation rather than assuming the annotation creates a runtime enum object.

Swift enum Format declares distinct named cases in its type system, and an exhaustive switch computes the suffix. This enum does not need raw values to return txt or rtf. Separate a typed choice from its display representation, and keep boundary parsing explicit when inputs begin as text.

Luau

Complete Luau console program:

main.luau

type Format = "plain" | "rich"
local function suffix(format: Format): string
  return if format == "plain" then "txt" else "rtf"
end
local format: Format = "rich"
print(suffix(format))

Swift

Complete program; compile the listed files together:

Format.swift

import Foundation
enum Format {
    case plain, rich
    var suffix: String {
        switch self {
        case .plain: return "txt"
        case .rich: return "rtf"
        }
    }
}

main.swift

import Foundation
let format = Format.rich
print(format.suffix)
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 Luau Developers

Practice on your own: Swift playground