不能下标[AnyObject]的值?索引类型为Int [英] Cannot subscript a value of [AnyObject]? with an index of type Int
本文介绍了不能下标[AnyObject]的值?索引类型为Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个扩展首先打开 self.objects
,然后调用它的下标。
从Swift 2开始,你也可以使用 guard statement :
var user2:PFUser
guard let userObject = self.objects?[indexPath.row] else {
//处理'self.objects'的情况'nil'并退出当前范围
}
user2 = userObject as! PFUser
This is in a class extending PFQueryTableViewController and I am getting the following error. The rows will be PFUser
only.
Why am I not able to cast it? Is there a way around this?
The error is:
Cannot subscript a value of [AnyObject]? with an index of type Int
...for this line:
var user2 = self.objects[indexPath.row] as! PFUser
解决方案
The problem isn't the cast, but the fact that self.objects
seems to be an optional array: [AnyObject]?
.
Therefore, if you want to access one of its values via a subscript, you have to unwrap the array first:
var user2: PFUser
if let userObject = self.objects?[indexPath.row] {
user2 = userObject as! PFUser
} else {
//handle the case of 'self.objects' being 'nil'
}
self.objects?[indexPath.row]
uses optional chaining to first unwrap self.objects
, and then call it's subscript.
As of Swift 2, you could also use the guard statement:
var user2: PFUser
guard let userObject = self.objects?[indexPath.row] else {
//handle the case of 'self.objects' being 'nil' and exit the current scope
}
user2 = userObject as! PFUser
这篇关于不能下标[AnyObject]的值?索引类型为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文