Menu
CoddyTech

Enums with Associated Values

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

C++ std::variant can store one of several typed alternatives, making it a closer counterpart to a Swift associated-value enum than a plain enum class. A tagged union requires additional manual agreement between its tag and payload. Swift enum cases directly attach their own payload shapes, and switch binds the data of the selected case. The source checks its Loaded variant safely with get_if, while Swift matches .loaded and extracts text. Associated values belong to individual instances; raw values are fixed representations of cases. Two loaded states may carry different strings without inventing different case declarations.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Waiting {};
struct Loaded { std::string text; };
using LoadState = std::variant<Waiting, Loaded>;

int main() {
LoadState state = Loaded{"ready"};
    if (const auto *loaded = std::get_if<Loaded>(&state)) std::cout << loaded->text << '\n';
    else std::cout << "waiting\n";
}

Swift

Complete program file: LoadState.swift.

enum LoadState { case waiting; case loaded(String) }

Complete program file: main.swift.

let state = LoadState.loaded("ready")
switch state {
case .waiting: print("waiting")
case .loaded(let text): print(text)
}
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