Skip to content

Instantly share code, notes, and snippets.

@jpmhouston
Created July 4, 2020 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmhouston/c2d827cf469e23c09bda7a901710313f to your computer and use it in GitHub Desktop.
Save jpmhouston/c2d827cf469e23c09bda7a901710313f to your computer and use it in GitHub Desktop.
Helpful Result extension functions failed() and suceeded() which return an optional of either the failure error or success value
extension Result {
func failed(else handleSuccess: ((Success) -> Void)? = nil) -> Failure? {
switch self {
case .success(let value):
handleSuccess?(value)
return nil
case .failure(let error):
return error
}
}
func succeeded(else handleFailure: ((Failure) -> Void)? = nil) -> Success? {
switch self {
case .success(let value):
return value
case .failure(let error):
handleFailure?(error)
return nil
}
}
}
// very useful if:
// - the success value is not wanted (perhaps its void?), only the error
// - or vice-versa you don't care what the error was (logged elsewhere?)
// if let error = authorize().failed() {
// print("Unable to get authorization, error: \(error)")
// }
// if let record = fetch().succeeded() {
// process(record)
// }
// - you store a result var then want to test error and value in separate if statements
// let updateResult = ....
// if let error = updateResult.failed() {
// log("updateItem failed, error \(error)")
// } else if let updatedEntity = updateResult.succeeded() {
// replaceOriginal(updatedEntity)
// }
// - seeking brevity at the sacrifice of simplicity, you want to unwrap a result within if or guard
// statements that capture the success value, but still want to have some failure handling
// if let loadedWidget = loadListToFindTestWidget().succeeded(else: { XCTFail("loadList failed, error \($0)") }) {
// widget = loadedWidget
// } else if let addedWidget = addTestWidget().succeeded(else: { XCTFail("addItem failed, error: \($0)") }) {
// widget = addedWidget
// } else {
// return
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment