Cannot subscript a value of [AnyObject]? with an index of type Int

user1406716 picture user1406716 · Apr 26, 2015 · Viewed 51.6k times · Source

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

enter image description here

Answer

Marcus Rossel picture Marcus Rossel · Apr 26, 2015

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`.
}

The expression self.objects?[indexPath.row] uses optional chaining to first unwrap self.objects, and then call its 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