无法将类型'__NSDictionaryM'的值强制转换为'NSArray'; [英] Could not cast value of type '__NSDictionaryM' to 'NSArray"

查看:158
本文介绍了无法将类型'__NSDictionaryM'的值强制转换为'NSArray';的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我代码的一部分:

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


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

这是来自Tumblr API的JSON的一部分:

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.

这是我的错误:

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

在这一行:

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

我不明白为什么.我对JSON和iOS还是很陌生,但是响应"对我来说就像字典,我不知道为什么它是NSArray,我也不知道如何解决这个问题.任何帮助将不胜感激.

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.

推荐答案

错误消息说

无法将 actual 类型的NSDictionary强制转换为 expected 类型的NSArray

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

[NSDictionary]表示字典数组,但是response的值显然是字典,由一对大括号表示.

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

实际上是

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

但是建议使用Swift本机集合类型

But it's recommended to use Swift native collection types

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

这篇关于无法将类型'__NSDictionaryM'的值强制转换为'NSArray';的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆