typestar

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

  1. Result<String, ProtestError> names both outcomes in the type.
  2. .success and .failure construct; guard picks between them.
  3. A switch unpacks the payload from whichever case arrived.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Errors & scope, step 23 of 27 in Language basics.

← Previous Next →

Result in other languages