Created
September 14, 2021 15:36
-
-
Save icanzilb/946b03420490cf7ff623a371dd9faa7e to your computer and use it in GitHub Desktop.
Result initialized with an async operation
This file contains hidden or 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 where Failure == Error { | |
init(_ task: @escaping () async throws -> Success) async { | |
self = await withCheckedContinuation { [task] continuation in | |
Task { | |
do { | |
continuation.resume(returning: .success(try await task())) | |
} catch { | |
continuation.resume(returning: .failure(error)) | |
} | |
} | |
} | |
} | |
} |
I am trying to wrap my head around this, is it possible to show an example on how it can be used at the call site?
I am trying to wrap my head around this, is it possible to show an example on how it can be used at the call site?
You get a result out of a throwing async task, like so:
let webResponse = await Result { try await URLSession.shared.data(from: url) }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or if you need a throwing variant: