A small command router chooses the work to run from a command string.

Route a command

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)
  1. command ← build

    1let command→ build = "build"  //@command="test", "deploy"2let message: String
  2. switch command

    4switch commandbuild {5case "build":6    message = "building app"
  3. message ← building app

    4switch command {5case "build":6    message→ building app = "building app"7case "test":
  4. print(message)

    15print(messagebuilding app)
    outputbuilding app
  1. command ← test

    1let command→ test = "test"2let message: String
  2. switch command

    4switch commandtest {5case "build":6    message = "building app"
  3. message ← running tests

    6    message = "building app"7case "test":8    message→ running tests = "running tests"9case "deploy":
  4. print(message)

    15print(messagerunning tests)
    outputrunning tests
  1. command ← deploy

    1let command→ deploy = "deploy"2let message: String
  2. switch command

    4switch commanddeploy {5case "build":6    message = "building app"
  3. message ← deploying site

    8    message = "running tests"9case "deploy":10    message→ deploying site = "deploying site"11default:
  4. print(message)

    15print(messagedeploying site)
    outputdeploying site
command router Many command-line tools start by reading a command name and selecting the matching action.