Menu
CoddyTech

Enums as Finite Choices

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

C++ enum class gives scoped enumerators and prevents implicit conversion to integers, yet still has an underlying integer representation and does not provide Swift-style exhaustive case checking. A Swift enum can declare a closed set of cases without choosing a numeric raw value. Swift methods and computed properties may switch on self to expose behavior. The examples describe read permission and return a locked label. Numeric casts and external serialization need explicit validation rather than assuming declaration order gives a portable meaning. Adding a Swift case exposes incomplete exhaustive switches that lack a catch-all branch.

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>
enum class Permission { Read, Write };

int main() {
Permission permission = Permission::Read;
    std::cout << (permission == Permission::Write ? "editable" : "locked") << '\n';
}

Swift

Complete program file: Permission.swift.

enum Permission {
    case read, write
    var canEdit: Bool {
        switch self { case .read: return false; case .write: return true }
    }
}

Complete program file: main.swift.

let permission = Permission.read
print(permission.canEdit ? "editable" : "locked")
challenge icon

Challenge

Easy

Implement Signal.next() -> Signal and Signal.label: String in Signal.swift. Cases are red, green, amber. The cycle is red to green to amber to red, and label is the lowercase case name. Input is one case name; output the next label.

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 Signal.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 Signal.red.next() == .green && Signal.green.next().next() == .red && Signal.amber.label == "amber"
}
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