Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Luau Developers course.
Luau can describe tagged table alternatives with singleton unions. Narrowing kind permits access to the saved branch's file field. The relationship exists in the checked type, while values remain ordinary tables at runtime, so data arriving from unchecked boundaries needs validation.
Swift enum cases carry associated values directly. A saved case wraps its own filename, while idle has no payload; switch binds the appropriate data and covers both alternatives. Associated values can differ for each instance of a case and are not fixed raw values.
Luau
Complete Luau console program:
main.luau
type Event = {kind: "saved", file: string} | {kind: "idle"}
local function describe(event: Event): string
return if event.kind == "saved" then string.upper(event.file) else "waiting"
end
print(describe({kind = "saved", file = "draft"}))
Swift
Complete program; compile the listed files together:
Event.swift
import Foundation
enum Event { case saved(String), idle }Functions.swift
import Foundation
func describe(_ event: Event) -> String {
switch event {
case .saved(let file): return file.uppercased()
case .idle: return "waiting"
}
}main.swift
import Foundation
print(describe(.saved("draft")))Challenge
EasyImplement Ticket enum with cases day(Int) and bundle(Int, Int). Its cost: Int equals the day price or bundle quantity times unit price. Input is day price or bundle quantity price; numeric fields are 0 through 100. Output cost.
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 Ticket.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 Ticket.day(11).cost == 11 && Ticket.bundle(4, 7).cost == 28 && Ticket.bundle(0, 9).cost == 0
}
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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Luau Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground