Enums with Associated Values
Lesson 40 of 48 in Coddy's Swift for Go Developers course.
Go can describe alternatives through an interface and several concrete structs, then use a type switch. That interface does not establish Swift-style exhaustive handling of a closed enum family. Swift associated-value enums directly declare the alternatives and their payload shapes.
The source Retry carries a seconds field and the target .retry carries an associated value bound in its switch. Different instances may have different payloads. Raw enum values, when used, instead provide fixed representations for cases.
Go: complete program
download.go
package main
type Download interface { download() }
ready.go
package main
type Ready struct { Path string }
func (Ready) download() {}
retry.go
package main
type Retry struct { Seconds int }
func (Retry) download() {}
main.go
package main
import (
"fmt"
)
func main() {
var outcome Download = Retry{Seconds: 4}
switch value := outcome.(type) {
case Ready: fmt.Println(value.Path)
case Retry: fmt.Printf("retry %d\n", value.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)")
}A Go type switch should consider unknown implementations when its interface is open. A Swift exhaustive enum switch exposes a newly added unhandled case during compilation unless a catch-all covers it.
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 Go 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