Associated values in Swift
Enum cases carry payloads; switch unpacks them.
// Enum cases can carry payloads; switch unpacks them.
enum RaceSignal {
case shorten(atMark: String)
case recall(sailNumbers: [Int])
}
func announce(_ signal: RaceSignal) -> String {
switch signal {
case .shorten(let mark):
return "Finish shortened at \(mark)"
case .recall(let numbers) where numbers.count > 2:
return "General recall"
case .recall(let numbers):
return "Individual recall: \(numbers)"
}
}
print(announce(.shorten(atMark: "leeward")))
print(announce(.recall(sailNumbers: [207, 88])))
print(announce(.recall(sailNumbers: [207, 88, 415])))
How it works
case shorten(atMark: String)stores data in the case.case .recall(let numbers) where ...binds and guards.- Case order matters: the guarded arm is tried first.
Keywords and builtins used here
IntRaceSignalStringannouncecasecountenumfuncletprintreturnswitchwhere
The run, in numbers
- Lines
- 20
- Characters to type
- 556
- Tokens
- 137
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 126 seconds.
Step 2 of 3 in Abstractions, step 20 of 27 in Language basics.