Practical Swift Programs
Config Selection
Programs often choose one configuration for local runs and another for production.
Pick a configuration
config_selection.swift
Replay: real traced execution (multi-file project)
let useProduction = false
let localHost = "localhost"
let productionHost = "api.example.com"
let host = useProduction ? productionHost : localHost
let port = useProduction ? 443 : 8080
let endpoint = "\(host):\(port)"
print(endpoint)
let useProduction = true
let localHost = "localhost"
let productionHost = "api.example.com"
let host = useProduction ? productionHost : localHost
let port = useProduction ? 443 : 8080
let endpoint = "\(host):\(port)"
print(endpoint)
useProduction ← false, localHost ← localhost, productionHost ← api.example.com
1let useProduction→ false = false //@useProduction=true2let localHost→ localhost = "localhost"3let productionHost→ api.example.com = "api.example.com"4let host→ localhost = useProductionfalse ? productionHostapi.example.com : localHostlocalhost5let port→ 8080 = useProductionfalse ? 443 : 80806let endpoint→ localhost:8080 = "\(hostlocalhost):\(port8080)"78print(endpointlocalhost:8080)outputlocalhost:8080
useProduction ← true, localHost ← localhost, productionHost ← api.example.com
1let useProduction→ true = true2let localHost→ localhost = "localhost"3let productionHost→ api.example.com = "api.example.com"4let host→ api.example.com = useProductiontrue ? productionHostapi.example.com : localHostlocalhost5let port→ 443 = useProductiontrue ? 443 : 80806let endpoint→ api.example.com:443 = "\(hostapi.example.com):\(port443)"78print(endpointapi.example.com:443)outputapi.example.com:443
Follow the Choice
useProductionstarts asfalse.- The host choice uses
localHost, sohostbecomeslocalhost. - The port choice uses the local port, so
portbecomes8080. endpointjoins them aslocalhost:8080.- The program prints
localhost:8080. | useProduction | chosen host | chosen port | endpoint | | --- | --- | ---: | --- | | false | localhost | 8080 | localhost:8080 | | true | api.example.com | 443 | api.example.com:443 |
configuration
A configuration value can select host names, ports, and other settings before the rest of a program starts.
Exercise: config_selection.swift
Reproduce localhost:8080, then set useProduction to true and predict api.example.com:443.