不能下标[AnyObject]的值?索引类型为Int

use*_*716 25 xcode ios parse-platform swift xcode6.3

这是在扩展PFQueryTableViewController的类中,我收到以下错误.这些行PFUser只是.
我为什么不能施展它?有没有解决的办法?

错误是:

Cannot subscript a value of [AnyObject]? with an index of type Int
Run Code Online (Sandbox Code Playgroud)

...对于这一行:

var user2 = self.objects[indexPath.row] as! PFUser
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Mar*_*sel 61

问题不在于演员,而是一个self.objects似乎是可选数组的事实:[AnyObject]?.
因此,如果要通过下标访问其中一个值,则必须先打开数组:

var user2: PFUser
if let userObject = self.objects?[indexPath.row] {
    user2 = userObject as! PFUser
} else {
    // Handle the case of `self.objects` being `nil`.
}
Run Code Online (Sandbox Code Playgroud)

表达式self.objects?[indexPath.row]使用可选链接首先解包self.objects,然后调用它的下标.


从Swift 2开始,您还可以使用guard语句:

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
Run Code Online (Sandbox Code Playgroud)


rud*_*ude 6

我遇到了同样的问题并解决了这个问题:

let scope : String = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] as! String
Run Code Online (Sandbox Code Playgroud)

对于您的情况,您可能会:

var user2 : PFUser = self.objects![indexPath.row] as! PFUser
Run Code Online (Sandbox Code Playgroud)