Skip to content

Instantly share code, notes, and snippets.

@PhanithNY
Forked from jegnux/Result+Catch.swift
Created September 23, 2021 09:54
Show Gist options
  • Save PhanithNY/563d29b63d09f5ff900e4a021bf590f2 to your computer and use it in GitHub Desktop.
Save PhanithNY/563d29b63d09f5ff900e4a021bf590f2 to your computer and use it in GitHub Desktop.
extension Result {
public func `catch`(_ handler: () throws -> Success) -> Result<Success, Error> {
flatMapError { _ in
.init { try handler() }
}
}
public func `catch`(_ handler: (Failure) throws -> Success) -> Result<Success, Error> {
flatMapError { error in
.init { try handler(error) }
}
}
public func get(default defaultValue: @autoclosure () -> Success) -> Success {
self.default(defaultValue)
}
public func `default`(_ handler: () -> Success) -> Success {
self.default { _ in handler() }
}
public func `default`(_ handler: (Failure) -> Success) -> Success {
switch self {
case .success(let success):
return success
case .failure(let error):
return handler(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment