Menu
CoddyTech

Switch and Patterns

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

C++ switch accepts integral or enumeration conditions and permits fallthrough between case bodies unless control exits. Swift switch supports strings and richer patterns and finishes a case automatically. Its coverage must include all possible inputs or a default. The source compares one-byte command characters; the target accepts whole string commands. Adjacent C++ case labels can share a body, while Swift groups patterns within one case. An explicit Swift fallthrough does not retest the next pattern, so it should not be used as a mechanical imitation of every C++ switch. Choose the controlling representation and branch behavior together.

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>

int main() {
char command = 'w';
    switch (command) {
        case 'w': case 's': std::cout << "write\n"; break;
        default: std::cout << "ignore\n"; break;
    }
}

Swift

Complete program file: main.swift.

let command = "w"
switch command {
case "w", "save": print("write")
default: print("ignore")
}
challenge icon

Challenge

Easy

Implement dayKind(_:). Input is an integer -10 through 20. Days 1 through 5 return work, 6 or 7 return rest, and every other value returns invalid.

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 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 dayKind(3) == "work" && dayKind(7) == "rest" && dayKind(-1) == "invalid"
}
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