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

5

25

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

Kiel answered 26/4, 2015 at 6:13 Comment(0)
E
61

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
Endogen answered 26/4, 2015 at 6:44 Comment(0)
G
6

I ran into the same issue and resolved it like this:

let scope : String = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] as! String

For your case, you might do:

var user2 : PFUser = self.objects![indexPath.row] as! PFUser
Glyconeogenesis answered 14/5, 2015 at 10:17 Comment(0)
R
3

My workaround would be..

  1. If you are certain that the tableview will contain only users try to typecast the objects Array of AnyObject to Array of PFUser. then use it.
Rhodia answered 26/4, 2015 at 6:38 Comment(2)
that still gives error, but this works, not sure why: var user2 = self.objects![indexPath.row] as! PFUserKiel
Because objects Array is optional [AnyObject]?Rhodia
H
1

Just add an ! (exclamation mark) after objects, like so:

var user2 = self.objects![indexPath.row] as! PFUser

That fixed it for me :)

Hauler answered 16/12, 2015 at 6:20 Comment(0)
E
0

I had a similar issue with the following line:

array![row]

I could not understand where the issue came from; if I replaced row with a number like 1 the code compiled and ran without any issues.

Then I had the happy thought of changing it to this:

array![Int(row)]

And it worked. For the life of me, I don't understand why giving an array an index of -1is theoretically legal, but there you go. It makes sense to me for subscripts to be unsigned, but maybe it's just me; I'll have to ask Chris about it.

Euphony answered 22/5, 2017 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.