Menu
CoddyTech

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 icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Go Developers

Practice on your own: Swift playground