【问题标题】:swift: cannot subscript a value of type [Dictionary<String, AnyObject>] with an index of type stringswift: 不能用字符串类型的索引下标 [Dictionary<String, AnyObject>] 类型的值
【发布时间】:2016-10-17 12:06:42
【问题描述】:

我正在尝试在 swift 3 中进行 json 解析。我收到了上述错误。我的解析技术如下:

if let responseData = data {
   do {
     let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments)
     if let dict = json as? [Dictionary<String, AnyObject>] {
        if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String {

         }               
     }           
   } catch {
       print("could not serialize")            
   }
}

我在行中收到错误:

if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String

请告诉我如何解决此问题

【问题讨论】:

  • 您正在创建一个ArrayDictionary。这是否有效。您需要使用Int 值来subscript
  • @New16 我的回复是字典数组
  • @EICaptainv2.0 我的回复是字典数组
  • [Dictionary&lt;String, AnyObject&gt;] => 数组(字典)。但是当你做dict["name"] 时,你使用dict 作为字典,而不是你之前声明的数组。这就是为什么你有错误。如果您的响应是一系列字典,显然,将其称为array,而不是dict,这太令人困惑了。并以不同的方式访问其价值。

标签: ios json swift3


【解决方案1】:

dict 属性是一个字典数组,而不是字典。 您可以访问以下名称的第一个元素:

dict.first?["name"]

【讨论】:

    【解决方案2】:

    dict 实际上是arr。创建一个循环来遍历它

    if let arr = json as? [Dictionary<String, AnyObject>] {
       for item in arr {
          if let localityName = item["name"] as? String,
             let localityId = item["_id"] as? String {
             print(localityName, localityId)
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多