HTTPURLResponse allHeaderFields Swift 3 Capitalisation

Update: this is a known issue.


allHeaderFields should return a case-insensitive dictionary because that is what the HTTP spec requires. Looks like a Swift error, I would file a radar or a bug report on .

Here is some sample code that reproduces the issue simply:

let headerFields = ["ETag" : "12345678"]
let url = URL(string: "http://www.example.com")!
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headerFields)!

response.allHeaderFields["eTaG"] // nil (incorrect)
headerFields["eTaG"] // nil (correct)

(Adapted from this Gist from Cédric Luthi.)


Based on @Darko's answer I have made a Swift 3 extension that will allow you to find any headers as case insensitive:

import Foundation


extension HTTPURLResponse {

    func find(header: String) -> String? {
        let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }

        if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
            return headerValue.1
        }
        return nil
    }

}