【问题标题】:Cannot subscript a value of type '[[String : Any]]' with an index of type 'String'无法使用“String”类型的索引为“[[String : Any]]”类型的值下标
【发布时间】:2018-02-19 14:21:52
【问题描述】:

我正在尝试从 json 数组中提取信息,但出现此错误

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

这里

     if let rev = place.details?["reviews"] as? [[String:Any]] {
   if let ver = rev["author_name"] as? String {    // <- IN THIS LINE I GET THE ERROR  

             }       
        } 

我知道如果我将类型转换为 [String : Any] 而不是 [[String:Any]] 它会起作用,但在这种情况下我必须将它转换为数组数组,否则它不会读取 json,那么如何我解决了这个问题?

【问题讨论】:

    标签: ios arrays json swift google-places-api


    【解决方案1】:

    [[String:Any]] 是一个数组。只能下标Int索引。

    例如,您必须遍历数组:

    if let reviews = place.details?["reviews"] as? [[String:Any]] {
        for review in reviews {
            if let authorName = review["author_name"] as? String {
               // do something with authorName
            }
        }
    }
    

    【讨论】:

    • 为什么不在这里使用forEach循环
    • @AzmalTech A for 循环对问题的描述性更强。
    【解决方案2】:

    您无法使用String 访问数组中的项目。你必须使用Int

    [[String:Any]]这是一个字典数组。

    【讨论】:

      【解决方案3】:

      [[String:Any]] 是一个二维数组。它只能使用 Int 索引进行下标。

      最好使用forEach 循环,例如

      if let reviews = place.details?["reviews"] as? [[String:Any]] {
          reviews?.forEach { review in
              if let authorName = review["author_name"] as? String {
                 // do something with authorName
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        我认为您在这里混淆了字典和数组。 如果要访问数组中的元素,则必须像这样使用Int 索引

        let a = ["test", "some", "more"] // your array
        let b = a[0] // print(b) = "test"
        

        如果你想访问字典中的一个元素,你可以通过它的键来访问它,在你的例子中是String

        let dict: [String: Any] = ["aKey": "someValue"]
        let value = dict["aKey"] // print(value) = "someValue"
        

        在您的情况下,您有一系列字典,每个字典都包含有关评论的信息。如果您想访问您的评论的作者,您必须首先从您的数组中取出评论字典,如下所示:

        if let reviews = place.details?["reviews"] as? [[String:Any]],
           let review = reviews[0] {
              // here you can access the author of the review then:
              if let author = review["author_name"] as? String {
                  // do something
              }
        }
        

        除了像我的示例那样只访问第一个评论之外,您还可以通过数组循环访问所有评论

        【讨论】:

        • 没错,我通常使用一个“安全”下标,它返回一个可选项,而不是在索引超出范围时崩溃。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-22
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多