Making Illegal States Unrepresentable
The [
URLSession
] completion handler receives three optional values:Data?
,URLResponse?
andError?
. 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
andURLResponse
, or (b) anError
. 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 theURLSession
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 populatedURLResponse
and a non-nil
error value (but noData
).