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
DataandURLResponse, or (b) anError. After all, it shouldn’t be possible to get a non-nilresponse and an error at the same time. Makes sense, right?It turns out that this is wrong. A
URLResponseencapsulates the server’s HTTP response headers, and theURLSessionAPI 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 populatedURLResponseand a non-nilerror value (but noData).