Switch and Patterns
Lesson 11 of 48 in Coddy's Swift for C Developers course.
C switch operates on an integer expression, including char and enum values, and cases can fall through unless control leaves them. Swift switch can match strings and richer patterns and has no implicit fallthrough. It must cover all possibilities or supply an appropriate default.
The source uses single-byte command characters, while Swift matches whole string values. Two adjacent C case labels share one body; Swift lists multiple patterns in one case. Neither a matching case nor its label implicitly performs string comparison in C, where a different explicit approach would be needed.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
char command = '?';
switch (command) {
case 'h':
case '?': puts("show help"); break;
case 'q': puts("close"); break;
default: puts("unknown"); break;
}
return 0;
}
Swift: complete program
main.swift
import Foundation
let command = "?"
switch command {
case "help", "?": print("show help")
case "quit": print("close")
default: print("unknown")
}Keep C break requirements separate from Swift behavior. A Swift case exits the switch after its body unless explicit control flow says otherwise.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence ScanPractice on your own: Swift playground