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])
}
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)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With