Could not cast value of type '__NSDictionaryM&

2019-01-27 06:30发布

问题:

This question already has an answer here:

  • Swift JSON error : Could not cast value of type '__NSDictionaryM' to 'NSArray' 3 answers

This is my part of my code:

let quotesData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary


var quoteDictionary: [NSDictionary]!
quoteDictionary = quotesData["response"] as! [NSDictionary]

This is part of the JSON from the Tumblr API:

{
  "meta": {
  "status": 200,
  "msg": "OK"
},
  "response": {
  "blog": {
  "title": "A Sea of Quotes",
  "name": "aseaofquotes",
  "total_posts": 10089,
  "posts": 10089,
  "url": "http://www.aseaofquotes.com/",
  "updated": 1461556819,
  "description": "",
  "is_nsfw": false,
  "ask": true,
  "ask_page_title": "Thanks in advance if you leave a nice message and/or correct quote sources. Please check FAQs before sending. I do not respond to Anonymous questions, but I may answer your anon question in the FAQ. :) Warning: It may take me a while to reply.",
  "ask_anon": true,
  "submission_page_title": "Submit A Quote",
  "share_likes": false
},
"posts": [
  {
    "blog_name": "aseaofquotes",
    "id": 143359277336,
    "post_url": "http://www.aseaofquotes.com/post/143359277336/marlon-james-a-brief-history-of-seven-killings",
    "slug": "marlon-james-a-brief-history-of-seven-killings",
    "type": "photo",
    "date": "2016-04-25 04:00:18 GMT",
    "timestamp": 1461556818,
    "state": "published",
    "format": "html",
    "reblog_key": "YiiqHC46",

ETC.

This is my error:

Could not cast value of type '__NSDictionaryM' (0x101925d38) to 'NSArray' (0x101925900).

On this line:

quoteDictionary = quotesData["response"] as! [NSDictionary]

I don't understand why. I'm pretty new to JSON and iOS but "response" looks like a dictionary to me, I don't know why it's an NSArray, I don't I don't know how to fix this. Any help would be greatly appreciated.

This is not a duplicate because the other post did not help me solve this problem.

回答1:

The error message says

Could not cast the actual type NSDictionary to the expected type NSArray

[NSDictionary] means an array of dictionaries, but the value of response is clearly a dictionary, represented by a pair of braces.

So it's actually

let quoteDictionary = quotesData["response"] as! NSDictionary

But it's recommended to use Swift native collection types

let quoteDictionary = quotesData["response"] as! Dictionary<String,AnyObject>


回答2:

quoteDictionary = quotesData["response"] as! [NSArray]

Now take this value from NSArray of dictionaries as [quoteDictionary][0] //returns first one

Now access that dictionary as [quoteDictionary][0][blog]