Menu
CoddyTech

Enums with Associated Values

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

A Lua tagged table can represent alternatives with different fields. The tag and payload are related by convention: this program expects a remote entry to carry host and retries. It explicitly rejects an unknown tag, but the language does not check that all producers construct the expected payload shape.

Swift enum cases can carry associated values with different types and counts. A switch binds each case's payload into local names and must cover every case. Associated data belongs to each constructed value; it is different from a fixed raw value assigned to a case.

Both examples describe a remote resource with a host and retry count. Swift keeps that shape in the enum declaration, removing the need to guess which fields exist after identifying the case. Apply the same approach to the ticket alternatives with their own payloads.

Complete Lua comparison program:

local resource = {kind = "remote", host = "docs", retries = 3}
if resource.kind == "local" then
  print(resource.name)
elseif resource.kind == "remote" then
  print(resource.host .. ":" .. resource.retries)
else
  error("unknown resource")
end

Complete Swift comparison program, compiled from these files:

Resource.swift

enum Resource {
    case local(String)
    case remote(String, Int)
}

main.swift

let resource = Resource.remote("docs", 3)
switch resource {
case .local(let name): print(name)
case .remote(let host, let retries): print("\(host):\(retries)")
}
challenge icon

Challenge

Easy

Implement 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") }
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