Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Python Developers course.
Python can model tagged data with separate classes, dataclasses, or tagged tuples. Swift enum cases can carry associated values, giving each alternative its own payload structure. The payload belongs to the particular enum value, not to one shared raw value for the case.
Switch patterns bind associated values into local names. Exhaustive switching then handles every variant. A raw-value enum assigns a fixed representation to a case; an associated-value enum can hold different payloads each time that case is constructed.
The example describes either a local file or a remote resource. It uses distinct payload shapes without computing the ticket cost asked for by the exercise.
Complete Python comparison program:
resource = ("remote", "docs", 3)
match resource:
case ("local", name):
print(name)
case ("remote", host, retries):
print(f"{host}:{retries}")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
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 Python 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