Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing information in [AnyHashable : Any] as NSDictionary

Tags:

ios

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

like image 338
mscarafo Avatar asked Dec 01 '16 18:12

mscarafo


Video Answer


2 Answers

try to use code below to unwrap your result:

if let dict = dict as NSDictionary? as! [String:Any]? {
  print(dict[key])
}
like image 127
EthanChou Avatar answered Oct 22 '22 07:10

EthanChou


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)")
    }
}
like image 44
OhadM Avatar answered Oct 22 '22 08:10

OhadM