Recently, I was reading a Paul Hudson article on the Swift Result type, which was introduced in Swift 5.0. In this article, he mentioned that Apple ha

URLSession & Result

submited by
Style Pass
2021-07-10 22:30:04

Recently, I was reading a Paul Hudson article on the Swift Result type, which was introduced in Swift 5.0. In this article, he mentioned that Apple hadn’t yet adopted Result into their own frameworks. This lead me to think, why not write an extension on URLSession to make a data task return Result<Data, Error> instead of Data?, URLResponse?, Error?. So that’s what I set about to do this past weekend.

Instead of returning a plain Error, I chose to create a NetworkError enum. This enum simply conforms to the Error protocol and allows us to define what type of error was encountered when attempting a network request. You can add cases to it as needed, but here is the one I will use for this example:

URLSession draws a line between the two error types that can be returned. Those that have to do with the transport, or going to and from the server, are passed in the Error? parameter of the completion handler. Server-side errors, on the other hand, are indicated by the HTTP status code of the response. These are specific to each server, but for the sake of this example, I will be treating any status code not in the range of 200…299 as an error (you could make the range of expected codes a variable if you like). Using NetworkError we can indicate which of these errors was encountered, and pass along the associated error or status code in the associated value of the enum.

While there is nothing inherently wrong with this code, as I start writing more network calls, a pattern emerges where I begin to repeat myself. I check the error, then I check the response, then I check to make sure there is data, and finally I do something with the data. I check the error, check the response, check the data, do something. Check error, check response, check data… I think you get the point.

Leave a Comment