Switch and Patterns
Lesson 11 of 48 in Coddy's Swift for R Developers course.
R switch can select by a character value using named alternatives, or by a numeric position with different rules. It is not an exhaustive pattern matcher, and unmatched selections need deliberate handling. Here an unnamed final alternative supplies the running default for the character selector.
Swift switch can match several patterns in one case and does not fall through to the next case automatically. It must cover every possible input, which may require default. Tuple, range and value-binding patterns can express decisions beyond literal equality.
The source and target group two commands into idle. Swift switch supports tuple and range patterns as well as literals and requires exhaustive handling. Keep the selector's actual type and the fallback rule visible when porting an R switch expression.
Complete R comparison program:
command <- "pause"
message <- switch(command, pause = "idle", stop = "idle", "running")
cat(message, "\n", sep = "")
Complete Swift comparison program, compiled from these files:
main.swift
let command = "pause"
switch command {
case "pause", "stop": print("idle")
default: print("running")
}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 R 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