Going from [AnyHashable : Any] to [String : NSObject] w/ b6?

Howdy,


Using CloudKit notifications which want [String : NSObject] but I have [AnyHashable : Any] vended by the system / app delegate.


The Swift 3 compiler in b6 won't allow me to do this:


if let userInfo = userInfo as? [String : NSObject] { ... }


It says that they aren't convertible. What's the best way to do this now? I'm sleep deprived and solutions are not filling my brain today.


Cheers.

From Twitter w/ Swift peeps, sounds like a compiler bug. For now:


as NSDictionary as! [String: AnyObject]

For anyone else struggling to get the cookies from an URLResponse, you need to jump through hoops like this now:

        guard let responseActual = response else {
            print("No response")
            return
        }
      
        guard let headers = responseActual.allHeaderFields as NSDictionary? as! [String:String]? else {
            print("wrong headers ... or so: \(responseActual.allHeaderFields)")
            return
        }
      
        guard let url = responseActual.url else {
            print("missing url from response: \(responseActual)")
            return
        }
      
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url)

If you’re looking for one specific header value, it’s much easier to cast the value rather than the entire dictionary. For example:

import Foundation

let response = HTTPURLResponse(url: URL(string: "")!, statusCode: 200, httpVersion: nil, headerFields: ["Some-Header": "some-value"])!
print(response.allHeaderFields["Some-Header"] as? String)
// -> Optional("some-value")
print(response.allHeaderFields["Some-Other-Header"] as? String)
// -> nil`

In your case, however, you’d like to pass

allHeaderFields
through to
HTTPCookie.cookies(withResponseHeaderFields:for:)
. The fact that this doesn’t work out of the box is a bug IMO (r. 27,805,863).
HTTPURLResponse.allHeaderFields
should be a
[String:String]
in order to match this API and others (most notably,
URLRequest.allHTTPHeaderFields
).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

in the latest Swift release, I had to cast it twice, like so:


userInfo as NSDictionary as! [String: AnyObject] as! [String : NSObject]


Let's hope they change this soon - ugly isn't it? :-)

This is horrendous. Swift is so broken right now.

Going from [AnyHashable : Any] to [String : NSObject] w/ b6?
 
 
Q