Accessing information in [AnyHashable : Any] as NSDictionary

convert anyhashable: any to dictionary
nsdictionary is not convertible to anyhashable any
nsdictionary to string
conditional cast from anyhashable any to nsdictionary always succeeds
swift any to string
cannot convert value of type '(string to expected argument type '(anyhashable : any))
how does anyhashable work
convert string to (string: any)

I am in the process of converting my code from Objective C to Swift. I have a code the calls an objective C method from a swift method. The obj C method returns an NSDictionary. Apparently Swift see this object as a type [AnyHashable : Any]. How do I read the information for this type? For example for a NSDictionary I would say NSString *s = [dict objectForKey:"key"]. What do I call in Swift to access the value in type [AnyHashable : Any]?

Thanks

try to use code below to unwrap your result:

if let dict = dict as NSDictionary? as! [String:Any]? {
  print(dict[key])
}

For example for a NSDictionary I would say NSString *s = [dict objectForKey:"key"​] . What do I call in Swift to access the value in type [AnyHashable : Any] ? The Any Hashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.. You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in Any Hashable instances:

You can use subscripts as in Objective-C.

Swift:

let s = dict["key"]

Objective-C:

NSString *s = dict["key"] //is equivalent to [dict objectForKey:"key"]

The AnyHashable type forwards equality comparisons and hashing require Hashable conformance by wrapping mixed-type keys in AnyHashable instances: wrapper over any collection with indices that support random access traversal. The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.

You can get like this:

let strShareLink = dict["key"] as! String

in swift

Hope, others will get help from this

(For convenience, the term dictionary refers to any instance of one of these classes For more information about object literals in Swift, see Literal Expression in The Swift such as object(forKey:) , you can access NSDictionary values by their keys using subscripting. init(dictionary: [AnyHashable : Any], copyItems: Bool). What is difference between Any,Hashable,AnyHashable in Swift 3? (3) I had the same problem. Notification banner appeared, but -application:didReceiveRemoteNotification:fetchCompletionHandler: method was not called.

Regarding AnyHashable, if you'll look at the documentation they give an example:

let descriptions: [AnyHashable: Any] = [
    AnyHashable("😄"): "emoji",
    AnyHashable(42): "an Int",
    AnyHashable(Int8(43)): "an Int8",
    AnyHashable(Set(["a", "b"])): "a set of strings"
]
print(descriptions[AnyHashable(42)]!)      // prints "an Int"

In my case I was parsing the response headers from a website so I had a key which was a string and the value was another JSON object.

The solution was straightforward, using the above syntax to obtain the entire object and cast it to string and use JSONSerialization to map it to a [String : Any] type:

if let jsonString = payload[AnyHashable("Key")] as? String,
   let data = jsonString.data(using: .utf8) {
   do {
       if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String : Any] {
           // json is now a [String : Any] type
   }
       else {
              print("JSON is invalid")
       }
      }
    catch {
           print("Exception converting: \(error)")
    }
}

So does JSON, NSArray and NSDictionary. But why? We will dive deep, bear with me. AnyObject -> Any. Swift focuses on using Value Types / immutable type in all cases Swift doesnot remove the type information during the boxing; Get unlimited access to the best stories on Medium — and support  Any vs. AnyObject in Swift 3.0. NSDictionary, and NSSet, which there’s a new type AnyHashable that can hold a value of any type conforming to the Swift Hashable protocol.

See https://swift.org/LICENSE.txt for license information Bridging to `Dictionary​<AnyHashable, AnyObject>` takes `O(n)` time, as the. // keys need to be fully rehashed Every time keys or values are accessed on the bridged `​NSDictionary`,. PFAnalytics provides an interface to Parse’s logging and analytics backend. Methods will return immediately and cache the request (+ timestamp) to be handled eventually. That is, the request will be sent immediately if possible or the next time a network connection is available.

The type information improves Swift access when you bridge from open var dueDates: [Any] open var dataDictionary: [AnyHashable : Any] open var We can make our NSArray , NSDictionary and NSSet collections safer  The AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type. You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in AnyHashable instances:

The initializer accepts NSDictionary as a parameter. its NSDictionary argument​, so it gets imported as taking Dictionary<AnyHashable, Any> . Objectives. Identify the usefulness of key-value pairs. Create an NSDictionary object with the literal syntax.; Access values in a dictionary by key. Access dictionary values within loops.

Comments
  • I would think the Swift equivalent of NSDictionary would be [AnyHashable : AnyObject] rather than [AnyHashable : Any]
  • Actually id s = dict["key"] would be closer, since id` is the anonymous object pointer in Objective-C.
  • I've tried that. I get a compiler error that reads Type '() -> [AnyHashable : Any]!' has no subscript members
  • I solved it. Turns out the objective C method I was calling to pass back the NSDictionary was let dict = object.getDict. I needed to say let dict = object.getDict(). Include the parens. The compiler error was not very helpful here.