Skip to content

Instantly share code, notes, and snippets.

@inamiy
Created September 1, 2021 13:16
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 inamiy/4116365bbdb658a864f41c374a4d5343 to your computer and use it in GitHub Desktop.
Save inamiy/4116365bbdb658a864f41c374a4d5343 to your computer and use it in GitHub Desktop.
Swift "async throws" to "async Result" https://twitter.com/inamiy/status/1433055765946798082
func asyncThrowsToAsyncResult<A, B>(_ f: @escaping (A) async throws -> B)
-> (A) async -> Result<B, Error>
{
{ a in
do {
return .success(try await f(a))
} catch {
return .failure(error)
}
}
}
func asyncResultToAsyncThrows<A, B>(_ f: @escaping (A) async -> Result<B, Error>)
-> (A) async throws -> B
{
{ a in
switch await f(a) {
case let .success(success):
return success
case let .failure(error):
throw error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment