Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Kotlin Developers course.
A Kotlin sealed hierarchy can model several alternatives with different payloads. Swift associated-value enums express that shape directly: each case can carry its own value types. A switch binds the payload only after matching its case, avoiding nullable fields that are meaningful in only some states. Raw-value enums map cases to fixed constants; associated values are data stored in each particular enum value. Use the right model for the domain rather than adding an ordinal or string tag beside unrelated fields. The example represents either a point or a message and formats each shape by binding exactly the data its case carries.
Kotlin
sealed class Event {
data class Point(val x: Int, val y: Int) : Event()
data class Note(val text: String) : Event()
}
fun describe(e: Event): String = when (e) {
is Event.Point -> "${e.x},${e.y}"
is Event.Note -> e.text
}
fun main() { println(describe(Event.Point(2, 5))); println(describe(Event.Note("ready"))) }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 Kotlin 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