Tuesday, April 3, 2018

Making Illegal States Unrepresentable

Ole Begemann (tweet):

The [URLSession] completion handler receives three optional values: Data?, URLResponse? and Error?. That makes 2 × 2 × 2 = 8 possible states, but how many of those are legal?


Brandon and Stephen made a small mistake: they assumed that the API will either return (a) a valid Data and URLResponse, or (b) an Error. After all, it shouldn’t be possible to get a non-nil response and an error at the same time. Makes sense, right?

It turns out that this is wrong. A URLResponse encapsulates the server’s HTTP response headers, and the URLSession API will always provide you with this value once it has received a valid response header, even if the request errors at a later stage (e.g. due to cancellation or a timeout). It’s thus expected behavior for the completion handler to contain a populated URLResponse and a non-nil error value (but no Data).

Comments RSS · Twitter

Leave a Comment