Menu
CoddyTech

Enums as Finite Choices

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

A Lua table can collect named constants, but it does not declare a closed enum type. Layout.roomy here is simply the number 12, and ordinary table entries can be changed or extended. A typo in a key can yield nil rather than a compiler error.

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 Lua table maps names directly to margins. The Swift enum keeps the choice separate from its computed margin, so the choice remains typed even when several cases might share a numeric result. Raw values and associated values are separate features, not required for this example.

Complete Lua comparison program:

local Layout = {compact = 4, roomy = 12}
local choice = Layout.roomy
print(choice)

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 Lua Developers

Practice on your own: Swift playground