【问题标题】:Swift 3 Type 'Any' has no subscript membersSwift 3 Type 'Any' 没有下标成员
【发布时间】:2016-09-29 19:56:57
【问题描述】:

我刚刚将我的项目转换为 Swift 3 我这里有这行代码:

let type = self.data[indexPath.row]["Type"] as? String

但现在我收到此错误:

Type 'Any' has no subscript members

为什么我会收到此错误,我应该修复它吗?

【问题讨论】:

标签: ios swift swift3


【解决方案1】:
let type = (self.data[indexPath.row] as? [String : String])?["Type"]

您需要将self.data[indexPath.row] 转换为字典。

【讨论】:

    【解决方案2】:

    您的data 或下标时返回的值,例如data[0] 具有 Any 类型,您正在尝试对其下标。

    确保编译器知道你得到的任何东西都是支持下标的已知类型。例如,like 和数组或字典。

    【讨论】:

      【解决方案3】:
      Even I was facing the same error 
      
      for item in 0...((currentSectionCells as! NSMutableArray).count - 1) {
      
                      if currentSectionCells[item]["isVisible"] as! Bool == true {
                      }   // error "Type 'Any' has no subscript "
                  }
      
      Then changed to code as below
      
      for item in 0...((currentSectionCells as! NSMutableArray).count - 1) {
                     if (item as! NSDictionary).value(forKey: "isVisible") as! Bool == true {
                      }
      }
      

      然后编译没有错误。

      【讨论】:

      • 这并不是对所提出问题的真正答案。接受的答案已经将强制转换指定为字典,对于 OP 的代码,您的答案既特定于您的用例(不回答问题),而且强制转换不安全。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多