title: NSURLSession data task response handling
body: <p>I am currently working on implementing a networking model that communicates with a REST API through HTTP in Swift using NSURLSession class.</p>
  
  <p>For preparing the request, I use this code:</p>
  
  <pre><code>    var request = URLRequest(url: requestURL) // url is "http://somethingsomething...
      request.httpMethod = "POST"
      request.setValue("application/json", forHTTPHeaderField: "Content-Type")
      request.httpBody = body
  </code></pre>
  
  <p>Now, I am sending the requests that way:</p>
  
  <pre><code>    session.dataTask(with: request) { data, response, error in
         // Parse the data, response and error
      }.resume()
  </code></pre>
  
  <p>My problem is that I want to check the <code>httpStatusCode</code> of the response in order to inform about possible errors, however, the <code>response</code> inside the completion block is of type <code>URLResponse</code>, not <code>HTTPURLResponse</code>. This means that I have to cast the <code>response</code> to the type <code>HTTPURLResponse</code>. So far I've thought of two ways to approach it - first is to add another error scenario which would handle the "couldn't cast to  HTTPURLResponse" scenario, the other way is to simply force the cast to <code>HTTPURLResponse</code>. The first option seems better but it could be just adding some useless code, because maybe the cast will always succeed? </p>
  
  <p>So basically, my question is - can I be sure that, if I send the requests to a HTTP server, the response will always be of <code>HTTPURLResponse</code> type? Or do I have to implement the code that handles a situation where the <code>response</code> object is of a different type or is a nil?</p>
  
  <p>Also, I think it would be good to mention that in my implementation if the completion block returns error that is not nil, the flow will return before trying to cast anything.</p>