[英]Cannot subscript a value of [AnyObject]? with an index of type Int
This is in a class extending PFQueryTableViewController and I am getting the following error. 这是在扩展PFQueryTableViewController的类中,我收到以下错误。 The rows will be PFUser
only. 这些行只是PFUser
。
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]?
问题不是演员,而是self.objects
似乎是一个可选的数组: [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. 表达式self.objects?[indexPath.row]
使用可选链接首先打开self.objects
,然后调用它的下标。
As of Swift 2, you could also use the guard statement : 从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
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
My workaround would be.. 我的解决方法是......
Just add an ! 只需添加一个! (exclamation mark) after objects, like so: 对象之后的(感叹号),如下所示:
var user2 = self.objects![indexPath.row] as! PFUser
That fixed it for me :) 那为我修好了:)
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. 如果我换成row
与一些像1
的代码编译并没有任何问题跑了。
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 -1
is theoretically legal, but there you go. 对于我的生活,我不明白为什么给数组索引-1
在理论上是合法的,但是你去了。 It makes sense to me for subscripts to be unsigned, but maybe it's just me; 对我来说,对于未签名的下标是有意义的,但也许只是我; I'll have to ask Chris about it. 我不得不问克里斯 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.