【问题标题】:Cannot subscript a value of type '[[String : AnyObject]]' with an index of type 'String'无法使用“String”类型的索引为“[[String : AnyObject]]”类型的值下标
【发布时间】:2017-03-30 06:59:41
【问题描述】:

我正在尝试获取特定位置的温度,但在尝试从 JSON 中提取信息时,我会发现此错误:

不能用“String”类型的索引为“[[String : AnyObject]]”类型的值下标

代码:

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let mainDictionary = json["main"] as? [[String : AnyObject]]
            {

                if let temp = mainDictionary["temp"] as! String
                {
                    print(temp)                                           

                }
            }

错误出现在以下行:

if let temp = mainDictionary["temp"] as! String

我已经尝试了多种在 slack 上找到的“解决方案”,但似乎都没有奏效......

提前致谢!

【问题讨论】:

  • 试试if let temp = mainDictionary[0]["temp"] as? String,如果不起作用,请在此处显示您的 JSON 响应。

标签: ios json swift api dictionary


【解决方案1】:

您将类型转换为:

[[String: AnyObject]]

当你应该像这样投射它时:

[String: AnyObject]

当您应该将类​​型转换为包含作为强键和作为值的任何对象的字典数组时,您执行此操作的方式将类型转换为包含字典的数组数组。

希望这有帮助:)

【讨论】:

  • 谢谢!这就是解决方案。
  • 很高兴我能帮助@DrWurffius
【解决方案2】:

应该是[String : AnyObject]?您将其转换为 [[String : AnyObject]] 表示字典数组

【讨论】:

  • 谢谢!这就是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多