Menu
CoddyTech

Enums with Associated Values

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

JavaScript tagged objects can model alternatives, but the program must validate that each tag has the appropriate payload properties. The source explicitly rejects unknown tags, while a missing file on a saved object would still violate its intended runtime contract. No static closed-union declaration is present.

Swift associated-value enums tie payload types to declared cases and support exhaustive switching. Matching .saved(let file) binds that value own String payload. Associated values differ from raw values fixed per case: two saved events can carry different filenames without declaring new cases.

JavaScript

Complete JavaScript console program:

main.js

function describe(event) {
  switch (event.kind) {
    case "saved": return event.file.toUpperCase();
    case "idle": return "waiting";
    default: throw new Error("unknown event");
  }
}
console.log(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 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 JavaScript Developers

Practice on your own: Swift playground