Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Ruby Developers course.
Ruby pattern matching can destructure a tagged hash and bind matching fields. The input is still a dynamic object: constructing an arbitrary hash does not statically prove it matches one of the intended cases. With no matching in branch, a case/in expression without a fallback can raise a pattern-match error.
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 enum declarations encode the alternatives and their payload shapes, and switch binds data for the active case. Both examples describe a remote resource, but the target removes the need for an informal tag-to-field convention. Per-instance payloads are distinct from fixed raw values.
Complete Ruby comparison program:
resource = {kind: :remote, host: "docs", retries: 3}
case resource
in {kind: :local, name:}
puts name
in {kind: :remote, host:, retries:}
puts "#{host}:#{retries}"
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
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 Ruby 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