Practical Swift Programs
Command Router
A small command router chooses the work to run from a command string.
Route a command
command_router.swift
Replay: real traced execution (multi-file project)
let command = "build"
let message: String
switch command {
case "build":
message = "building app"
case "test":
message = "running tests"
case "deploy":
message = "deploying site"
default:
message = "unknown command"
}
print(message)
let command = "test"
let message: String
switch command {
case "build":
message = "building app"
case "test":
message = "running tests"
case "deploy":
message = "deploying site"
default:
message = "unknown command"
}
print(message)
let command = "deploy"
let message: String
switch command {
case "build":
message = "building app"
case "test":
message = "running tests"
case "deploy":
message = "deploying site"
default:
message = "unknown command"
}
print(message)
command ← build
1let command→ build = "build" //@command="test", "deploy"2let message: Stringswitch command
4switch commandbuild {5case "build":6 message = "building app"message ← building app
4switch command {5case "build":6 message→ building app = "building app"7case "test":print(message)
15print(messagebuilding app)outputbuilding app
command ← test
1let command→ test = "test"2let message: Stringswitch command
4switch commandtest {5case "build":6 message = "building app"message ← running tests
6 message = "building app"7case "test":8 message→ running tests = "running tests"9case "deploy":print(message)
15print(messagerunning tests)outputrunning tests
command ← deploy
1let command→ deploy = "deploy"2let message: Stringswitch command
4switch commanddeploy {5case "build":6 message = "building app"message ← deploying site
8 message = "running tests"9case "deploy":10 message→ deploying site = "deploying site"11default:print(message)
15print(messagedeploying site)outputdeploying site
command router
Many command-line tools start by reading a command name and selecting the matching action.