Created
September 1, 2021 13:16
-
-
Save inamiy/4116365bbdb658a864f41c374a4d5343 to your computer and use it in GitHub Desktop.
Swift "async throws" to "async Result" https://twitter.com/inamiy/status/1433055765946798082
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
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