Result in Swift
Success or failure as a value, switched like any enum.
// Result stores success or failure as a value you can pass around.
enum ProtestError: Error {
case filedLate
}
func hearProtest(minutesAfter: Int) -> Result<String, ProtestError> {
guard minutesAfter <= 90 else {
return .failure(.filedLate)
}
return .success("Protest heard, redress granted")
}
// A Result switches like any enum.
for delay in [30, 120] {
switch hearProtest(minutesAfter: delay) {
case .success(let outcome):
print(outcome)
case .failure(let error):
print("Dismissed: \(error)")
}
}
How it works
Result<String, ProtestError>names both outcomes in the type..successand.failureconstruct; guard picks between them.- A
switchunpacks the payload from whichever case arrived.
Keywords and builtins used here
IntProtestErrorStringcaseelseenumforfuncguardhearProtestinletprintreturnswitch
The run, in numbers
- Lines
- 20
- Characters to type
- 501
- Tokens
- 98
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 90 seconds.
Step 2 of 3 in Errors & scope, step 23 of 27 in Language basics.