Advanced Swift: Error Handling, Episode 6: The Result Type | Kodeco, the new raywenderlich.com

Using a result type is a great way to deal with asynchronous results that may end in error. We explore this useful algebraic type.


This is a companion discussion topic for the original entry at https://www.kodeco.com/1940818-advanced-swift-error-handling/lessons/6

Hi Team,

Could you give some recommendations regarding when it makes sense to use the throw syntax over returning the Result type from the function?

I’ve watched the videos here as well as read these articles:

And everything seem to indicate the using the Result type is a superior option. We can pass the result type down the chain for functional programming, store it for later usage and we can ensure that the error is always strongly typed.

Are there any situations where throwing an error is a superior pattern?

1 Like

With the advent of async/await I think the need for Result is greatly reduced. Now, more than ever you want to use throws! :smiley:

Consider the function

func fetchUser(id: ID, process: (Result<User, Error>) -> Void)

This function fetches a user, which could take a long time, could fail. The function returns right away and then you process the result in a callback closure. The Result notifies you if there was an error in the fetching process. However, now, you can write it like this:

func fetchUser(id: ID) async throws -> User

Generally, I think this is a more straightforward way of writing it that you should prefer.

Results still has its place though. Because it lets you build functional chains of processing with streams or if you are using something like combine.

3 Likes

Very interesting, thank you Ray. So sounds like Result was born out of necessity and became popular as it was allowing to do a bit more. But now that it no longer a necessity it may go out of fashion. Got it, thank you :slight_smile:

1 Like

Great Question @allanspreys. And thank you @rayfix for your swift response.