Swift:无法将“__NSCFArray”类型的值转换为“NSDictionary” [英] Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'

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

问题描述

我有来自网站的JSON数据。我做了主字典,我可以解析除一个子字典之外的每个数据。我收到错误Swift:无法将类型__NSCFArray'的值转换为NSDictionary



我的数据示例。我无法解析天气,但我可以解析所有其他字典,如wind

  [name:Mountain View,id:5375480,weather:(
{
description =sky is clear;
icon = 01n;
id = 800;
main = Clear;
}
),base:cmc station,wind:{
deg =129.502;
speed =1.41;

代码片段

让$ winder =主要词典[风]为! [String:AnyObject 
let speed = windDictionary [speed] as! double
print(speed)
let weather = mainDictionary [weather] as! [String:AnyObject]
print(weather)


解决方案

p>代表你的评论...我会说windDictionary是字典...

 字典在JSON中表示与{}和
数组表示与[] //在打印的响应中,您可能有数组()

所以,你的天气部分是字典数组...你必须解析它像

  let weather = mainDictionary [weather ] as! [[String:AnyObject]] //虽然请不要使用强制解开..或者使用`if let`或`guard`语句


I have JSON data from website. I made the main dictionary and I can parse every data except one sub dictionary. I get the error "Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'"

This example of my data. I cannot parse "weather" but I can parse all other dictionaries like "wind".

   ["name": Mountain View, "id": 5375480, "weather": (
        {
        description = "sky is clear";
        icon = 01n;
        id = 800;
        main = Clear;
    }
), "base": cmc stations, "wind": {
    deg = "129.502";
    speed = "1.41";

Snippet of code

 let windDictionary = mainDictionary["wind"] as! [String : AnyObject
 let speed = windDictionary["speed"] as! Double
 print(speed)
 let weather = mainDictionary["weather"] as! [String : AnyObject]
 print(weather)

解决方案

on behalf your comment...I would say windDictionary is Dictionary...

Dictionary denotes in JSON with {} and 
Array denotes with [] // In printed response you may have array with ()

So, your weather part is Array of Dictionary...You have to parse it like

 let weather = mainDictionary["weather"] as! [[String : AnyObject]]  // although please not use force unwrap .. either use `if let` or `guard` statement

这篇关于Swift:无法将“__NSCFArray”类型的值转换为“NSDictionary”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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