Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Java Developers course.
Java 17 sealed interfaces and record implementations can describe a finite family of values with different payloads. Swift associated-value enums directly attach data to each case. Each enum value chooses one case and carries the payload for that case.
The examples model either a successful download path or a retry suggestion with a delay. Swift switch binds a payload using let in its pattern. These payloads belong to individual values, unlike one fixed raw value assigned to an enum case declaration.
Java: complete program
Download.java
public sealed interface Download permits Ready, Retry {}Ready.java
public record Ready(String path) implements Download {}Retry.java
public record Retry(int seconds) implements Download {}Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
Download outcome = new Retry(4);
if (outcome instanceof Ready ready) System.out.println(ready.path());
else if (outcome instanceof Retry retry) System.out.println("retry " + retry.seconds());
}
}Swift: complete program
Download.swift
import Foundation
enum Download {
case ready(path: String)
case retry(seconds: Int)
}main.swift
import Foundation
let outcome: Download = .retry(seconds: 4)
switch outcome {
case .ready(let path): print(path)
case .retry(let seconds): print("retry \(seconds)")
}An associated value is not a shared mutable field on a singleton Java enum constant. Two values of the same Swift case can carry different associated data.
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 Java 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