2016-04-25 13 views
1

」にタイプ '__NSDictionaryM' の値をキャストできませんでした:は、これは私のコードの私の一部ですNSArrayの「

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


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

これは、TumblrのAPIからJSONの一部です:

{ 
    "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なのか分かりませんが、これを修正する方法がわかりません。どんな助けでも大歓迎です。

他の投稿がこの問題を解決するのに役立たなかったので、これは重複していません。今[quoteDictionary][0][blog]

答えて

2

として辞書は、エラーメッセージが

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

[NSDictionary]はの配列を意味言うことを最初にアクセスする1

を返す// [quoteDictionary][0]として今NSArray of dictionariesからこの値を取る

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

しかし、responseの値は明らかに辞書、repreです中括弧のペアによって送られる。

だから、実際に

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

だが、

let quoteDictionary = quotesData["response"] as! Dictionary<String,AnyObject> 
スウィフトネイティブのコレクション型を使用することをお勧めします
関連する問題