Last active
December 10, 2023 19:24
-
-
Save jegnux/500b0975375ebd59c7df039c575d51f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Examples
Try all blocks in cascade until getting a success and extract the value, or
throw
if all blocks failCompare with regular do/catch
Try all blocks in cascade until getting a success and extract the value, or return the
default
value if all blocks failCompare with regular do/catch
Try all blocks in cascade until getting a success and extract the value, or return the
value
from the non-throwingdefault
blockCompare with regular do/catch
Thanks
Thanks @ABridoux for the help