Menu
CoddyTech

Enums with Associated Values

Lesson 40 of 48 in Coddy's Swift for PHP Developers course.

PHP enums provide fixed cases, but their backing scalar values are not arbitrary per-instance payloads. This example instead uses a tagged associative array to carry a remote host and retry count. The array's tag-to-field relationship is a convention that ordinary runtime array typing does not enforce.

Swift enum cases can carry associated values with different types and counts. A switch binds each case's payload into local names and must cover every case. Associated data belongs to each constructed value; it is different from a fixed raw value assigned to a case.

The target enum declares its alternatives and their payload shapes together. Switch binds only the fields belonging to the active case. Keep fixed case representations separate from data that changes for each constructed resource when designing the ticket variants.

Complete PHP comparison program:

<?php
declare(strict_types=1);
$resource = ["kind" => "remote", "host" => "docs", "retries" => 3];
echo match ($resource["kind"]) {
    "local" => $resource["name"],
    "remote" => $resource["host"] . ":" . $resource["retries"],
    default => throw new InvalidArgumentException("unknown resource")
}, "\n";

Complete Swift comparison program, compiled from these files:

Resource.swift

enum Resource {
    case local(String)
    case remote(String, Int)
}

main.swift

let resource = Resource.remote("docs", 3)
switch resource {
case .local(let name): print(name)
case .remote(let host, let retries): print("\(host):\(retries)")
}
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 PHP Developers

Practice on your own: Swift playground