I have some API logic written as a collection of throwing functions:
func getModel() async throws -> Model
When calling these from tasks in a SwiftUI view, I want to catch the error so I can display an error message if necessary. To do this, I have a Result<Model, Error> state variable:
@State var model: Result<Model, Error>?
To call the API function and get its result as a Result, this is the best code I've been able to write:
do {
model = .success(try await getModel())
} catch let e {
model = .failure(e)
}
I can't help feeling there's a better way of doing this which I'm missing - the do/catch usage feels like it should be unnecessary.
Is there some easier way I can call throwing functions and get their successful return or their thrown error as a Result?
You can pretty easily write your own extension to do this, or just call the equivalent manually:
Then you can create the
Resultusinglet result = await Result { try await getModel() }. Or evenlet result = await Result(getModel).