'[AnyHashable : Any]?' is not convertible to '[String : Any]'

In the painstaking porting to Swift 3.0 I am getting this error I am not making a sense of it in code:

guard let userInfo = notification.userInfo as? [String: Any] else {return}

How do I fix the code to make it compilable?

Answered by OOPer in 174274022

See this thread.

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


You can write something like this:

guard let userInfo = notification.userInfo as NSDictionary? as? [String: Any] else {return}

But, `[String: Any]` is not something useful in Swift.


Why don't you just unwrap it and use `userInfo` of `[AnyHashable: Any]` directly in your code?

        guard let userInfo = notification.userInfo else {return}
        if let myData = userInfo["myData"] as? String {
            //Do something with myData
            //...
        }

You cannot cast an optional to a non-optional. You first have to unwrap the optional, and then cast it to the type you think it might be.

Accepted Answer

See this thread.

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


You can write something like this:

guard let userInfo = notification.userInfo as NSDictionary? as? [String: Any] else {return}

But, `[String: Any]` is not something useful in Swift.


Why don't you just unwrap it and use `userInfo` of `[AnyHashable: Any]` directly in your code?

        guard let userInfo = notification.userInfo else {return}
        if let myData = userInfo["myData"] as? String {
            //Do something with myData
            //...
        }

If fact removing the cast does not give any problem when I use it in:

guard let reasonForChange = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? String else {return}

This is fine. Casting to NSDictionary does not work, though.

Thank you very much, thi also works when I need to get a [String: Double].

It seems Swift 3 is more easygoing about casting geneic types.

Try this --> [https://not.justsolutionsproducts.com/not-convertible-to-string-any-fixed/)

'[AnyHashable : Any]?' is not convertible to '[String : Any]'
 
 
Q