Menu
CoddyTech

Enums with Associated Values

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

R can model alternatives with tagged lists, whose elements differ by kind. The switch expression selects the relevant fields, but an ordinary list does not enforce that remote carries host and retries. A constructor or validation function must establish that relationship for arbitrary incoming data.

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.

Swift associated-value cases encode those payload shapes directly. The switch binds the values for the active case and covers every alternative. Distinguish per-resource payloads from fixed category labels, including when a source model uses factors or class attributes elsewhere.

Complete R comparison program:

resource <- list(kind = "remote", host = "docs", retries = 3L)
description <- switch(resource$kind,
  local = resource$name,
  remote = paste0(resource$host, ":", resource$retries),
  stop("unknown resource"))
cat(description, "\n", sep = "")

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

Practice on your own: Swift playground