Menu
CoddyTech

Enums with Associated Values

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

A tagged C union uses a separate discriminator and overlapping payload storage, with program logic maintaining which member is meaningful. Swift associated-value enums tie each case to its declared payload shape in the type system. Each value chooses one case and carries data for that case.

The source factory initializes both the retry tag and seconds member, then the switch reads the appropriate payload. Swift matches .retry and binds its associated seconds value directly. Different values of the same case can carry different data; this is separate from an enum case raw value.

C: complete program

download.h

#ifndef DOWNLOAD_H
#define DOWNLOAD_H
typedef enum { DOWNLOAD_READY, DOWNLOAD_RETRY } DownloadKind;
typedef struct { DownloadKind kind; union { const char *path; int seconds; } data; } Download;
#endif

ready.h

#ifndef READY_H
#define READY_H
#include "download.h"
static inline Download ready(const char *path) { Download value = {.kind=DOWNLOAD_READY, .data.path=path}; return value; }
#endif

retry.h

#ifndef RETRY_H
#define RETRY_H
#include "download.h"
static inline Download retry(int seconds) { Download value = {.kind=DOWNLOAD_RETRY, .data.seconds=seconds}; return value; }
#endif

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "ready.h"
#include "retry.h"

int main(void) {
Download outcome = retry(4);
    switch (outcome.kind) {
        case DOWNLOAD_READY: puts(outcome.data.path); break;
        case DOWNLOAD_RETRY: printf("retry %d\n", outcome.data.seconds); break;
    }
    return 0;
}

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)")
}

Do not read an arbitrary union member while ignoring the C tag. Swift pattern matching provides a safer direct representation of the intended alternatives.

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 C Developers

Practice on your own: Swift playground