Friday, April 3, 2020

Swift Bridging of allHeaderFields

Cédric Luthi:

I don’t do a lot of swift. But every time I do, I stumble on obscure quirks. Last case in point: HTTPURLResponse allHeaderFields is now case-sensitive.

This seems to be because the property is implemented using an NSDictionary subclass. Apple notes:

In Objective-C, the returned dictionary of headers is case-preserving during the set operation (unless the key already exists with a different case), and case-insensitive when looking up keys.

But Swift bridging converts it to a regular Swift Dictionary, which is case-sensitive (though looser about Unicode).

In general, you can avoid the bridging by casting:

allHeaderFields as NSDictionary

In this particular case, there is an extra API in Catalina and iOS 13 to look up header fields in a case-insensitive way:

func value(forHTTPHeaderField field: String) -> String?

This is an interesting case study of the current Cocoa documentation because:

I would rather have a single version of the documentation that includes all the information, with the only difference being the syntax used. Otherwise, I have to switch back and forth to make sure I’m not missing anything.

Previously:

Comments RSS · Twitter

Leave a Comment