Last active
December 20, 2021 02:34
-
-
Save JadenGeller/7a4ae11be08a6798002775bbd07887e3 to your computer and use it in GitHub Desktop.
Abort
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
struct Abort<Failure>: Error { | |
var failure: Failure | |
init(_ failureType: Failure.Type, _ failure: Failure) { | |
self.failure = failure | |
} | |
enum Recovery<Success> { | |
case success(Success) | |
case failure(Failure) | |
var success: Success { | |
get throws { | |
switch self { | |
case .success(let success): | |
return success | |
case .failure(let failure): | |
throw Abort(Failure.self, failure) | |
} | |
} | |
} | |
var failure: Failure { | |
get throws { | |
switch self { | |
case .success: | |
throw Abort<Void>() | |
case .failure(let failure): | |
return failure | |
} | |
} | |
} | |
} | |
static func recover<Success>(_ failureType: Failure.Type, _ body: () throws -> Success) throws -> Recovery<Success> { | |
do { | |
return .success(try body()) | |
} | |
catch let error as Self { | |
return .failure(error.failure) | |
} | |
} | |
} | |
extension Abort where Failure == Void { | |
init() { | |
self.init(Void.self, ()) | |
} | |
static func recover<Success>(_ body: () throws -> Success) throws -> Success? { | |
do { | |
return try body() | |
} | |
catch _ as Self { | |
return nil | |
} | |
} | |
static func retry<Succcess>(_ body: () throws -> Succcess) throws -> Succcess { | |
while true { | |
guard let success = try recover(body) else { continue } | |
return success | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment