Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Rust Developers course.
Rust enum variants and Swift associated-value cases can carry different payload shapes. Matching identifies a variant before binding the appropriate data, avoiding unrelated optional fields and informal string tags. The Rust describe function borrows its Event so it can inspect an owned String without consuming the event; another match could deliberately move that payload. Swift uses its value semantics and associated-value bindings rather than the same borrow syntax. Both examples distinguish a point from a note and handle every alternative. Per-instance associated data is different from a fixed raw-value representation for a case, so choose the form that matches the domain.
Rust
enum Event { Point(i32, i32), Note(String) }
fn describe(event: &Event) -> String {
match event { Event::Point(x, y) => format!("{},{}", x, y), Event::Note(text) => text.clone() }
}
fn main() {
println!("{}", describe(&Event::Point(2, 5)));
println!("{}", describe(&Event::Note("ready".into())));
}
Swift
enum Event { case point(Int, Int); case note(String) }
func describe(_ event: Event) -> String {
switch event {
case .point(let x, let y): return "\(x),\(y)"
case .note(let text): return text
}
}
print(describe(.point(2, 5)))
print(describe(.note("ready")))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 Rust 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