Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Dart Developers course.
Dart sealed hierarchies let pattern matching distinguish variants with different data. Swift enum associated values put those alternatives directly into one enum. Each instance selects one case and carries only that case's payload. Associated values differ from raw values: the payload can vary from instance to instance. A switch binds the payload to local names and must cover all cases. The example represents either text or a line break, rather than using a nullable field plus a separate tag that could become inconsistent.
Complete Dart program. Each labelled block is a separate file.
Piece.dart
sealed class Piece {}
final class TextPiece extends Piece {
final String text;
TextPiece(this.text);
}
final class LineBreak extends Piece {}main.dart
import 'Piece.dart';
void main() {
final Piece piece = TextPiece('memo');
switch (piece) {
case TextPiece(:final text): print(text.toUpperCase());
case LineBreak(): print('<break>');
}
}Complete Swift program. Each labelled block is a separate file.
Piece.swift
import Foundation
enum Piece { case text(String), lineBreak }main.swift
import Foundation
let piece = Piece.text("memo")
switch piece {
case .text(let text): print(text.uppercased())
case .lineBreak: print("<break>")
}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 Dart 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