JSharpp
JSharpp

Reputation: 559

Accessing information within a NSDictionary

I am trying to parse out data from a NSDictionary but am having trouble. Whenever I try to access this information it prints nil.

NSDictionary:

{
"-LTR7P8PFWHogjlBENiJ" =     {
    filmid = 335983;
    rating = "5.5";
    review = Ehh;
};
}

CODE:

let dict = info.value as! NSDictionary
print(dict) //prints about NSDict
print(dict["review"] as? String) //prints nil

What would be the correct method to print "Ehh" from the NSDictionary?

Upvotes: 0

Views: 73

Answers (2)

Kamran
Kamran

Reputation: 15238

You can get the review value as below,

typealias JSON = [String: Any]
let dictionary: JSON = [
    "-LTR7P8PFWHogjlBENiJ": [
        "filmid": 335983,
        "rating": "5.5",
        "review": "Ehh"
    ]
]

if let reivew = (dictionary.first?.value as? JSON)?["review"] as? String {
    print(reivew)
}

For NSDictionary, you might have to use this as below,

let dict = info.value as! NSDictionary
if let reivew = (dict.allValues.first as? JSON)?["review"] as? String {
    print(reivew)
}

Upvotes: 1

dvp.petrov
dvp.petrov

Reputation: 1120

You have outer dictionary wrapper of your searched result, with string key -LTR7P8PFWHogjlBENiJ

So your code currently searches key review in the outer dict.

Upvotes: 2

Related Questions