Swift 3 Type 'Any' has no subscript member

2020-06-16 02:42发布

I just converted my project to Swift 3 I have this line of code here:

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

but now I get this error:

Type 'Any' has no subscript members

Why am I getting this error and do I fix it?

标签: ios swift swift3
3条回答
家丑人穷心不美
2楼-- · 2020-06-16 02:52
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 {
                }
}

Then it compiled without error.

查看更多
混吃等死
3楼-- · 2020-06-16 03:03

Either your data or the value returned when you subscript it, e.g. data[0] has the Any type, which you're trying to subscript.

Make sure that the compiler knows that whatever you get is a known type which supports subscripting. Like and array or dictionary for example.

查看更多
来,给爷笑一个
4楼-- · 2020-06-16 03:04
let type = (self.data[indexPath.row] as? [String : String])?["Type"]

You need to cast self.data[indexPath.row] to a dictionary.

查看更多
登录 后发表回答