Menu
CoddyTech

Enums with Associated Values

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

A C# enum names integral values and cannot attach a different payload shape to each member. C# programs often model such alternatives with a class hierarchy, records, or an explicit tag plus fields. Swift enums support associated values directly: each case can carry its own payload, and a switch binds the data belonging to that case. The example represents loading state as waiting or a text message. A state with a message cannot accidentally expose a nonexistent numeric field. This is different from calculating ticket prices. Associated values are instance data; raw values, when used, are fixed representations assigned to cases.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
abstract class LoadState { }
sealed class Waiting : LoadState { }
sealed class Loaded : LoadState { public readonly string Text; public Loaded(string text) { Text = text; } }

class Program
{
    static void Main()
    {
        LoadState state = new Loaded("ready");
        var loaded = state as Loaded;
        Console.WriteLine(loaded == null ? "waiting" : loaded.Text);
    }
}

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