Skip to content

Instantly share code, notes, and snippets.

@mclaughj
Last active September 1, 2016 15:30
Show Gist options
  • Save mclaughj/a0425cab3325d449e35f8c1224a69a00 to your computer and use it in GitHub Desktop.
Save mclaughj/a0425cab3325d449e35f8c1224a69a00 to your computer and use it in GitHub Desktop.
Example from @cocoaphony at try! Swift NYC (Sep. 1, 2016)
struct Token {
var value: String
}
struct Credential {
var username: String
var password: String
}
enum Result<Value> {
case success(Value)
case failure(Error)
}
func login(credential: Credential, callback: (token: Token?, error: Error?)) {
// Now we need to check four cases:
//
// result
// nil value
// ┌────────┬────────┐
// nil │ ?? │ ✓ │
// error ├────────┼────────┤
// value │ ✓ │ ?? │
// └────────┴────────┘
//
// ...even though only two make logical sense. Having both
// an error value and a result value is a case we have to
// test for.
}
// By using the Result enum type instead of a tuple with two
// optional values, we force either a success value or a
// failure value.
func login(credential: Credential, callback: Result<Token>) {
switch callback {
case .success(let token):
// Handle success
break
case .failure(let error):
// Handle error
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment