【问题标题】:Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'Swift:无法将“__NSCFArray”类型的值转换为“NSDictionary”
【发布时间】:2016-01-12 10:49:33
【问题描述】:

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

我的数据的这个例子。我无法解析 "weather",但我可以解析所有其他字典,例如 "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";

代码片段

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

【问题讨论】:

  • 它似乎是一个数组,而不是字典。试试 let weather = mainDictionary["weather"] as? [任何对象]
  • 天气不是字典......let weather = mainDictionary["weather"] as! [[String : AnyObject]]
  • 但风字典语法相同
  • @ElCaptain 我认为是对的
  • 如果你看一下,wind 后面只有 {},什么是 JSON 中的字典。然而天气有 ({ }) 这意味着字典被包裹在一个数组中。

标签: ios swift dictionary swift2


【解决方案1】:

代表您的评论...我会说 windDictionary 是 Dictionary...

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

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

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

【讨论】:

  • 不,没关系,现在好多了。感谢您的编辑。 :)
  • 谢谢,我一直在寻找这样的东西。 :)
猜你喜欢
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
  • 2016-02-01
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多