本文介绍了不能为 [AnyObject] 的值添加下标?具有 Int 类型的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在扩展 首先解包self.objects,然后调用它的下标.

从 Swift 2 开始,您还可以使用 保护声明:

var user2: PFUser守卫让 userObject = self.objects?[indexPath.row] else {//处理 `self.objects` 为 `nil` 的情况并退出当前作用域.}user2 = userObject as!PF用户

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

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

这篇关于不能为 [AnyObject] 的值添加下标?具有 Int 类型的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:39