[AnyObject]?没有名为'下标'的成员

Isu*_*uru 8 arrays optional ios swift

我正在将核心数据数据库中的对象列表加载到表视图中.

class ScheduleViewController: UITableViewController {

    private var items: [AnyObject]?

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let itemCount = items?.count {
            return itemCount
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("DayScheduleCell", forIndexPath: indexPath) as DayScheduleCell

        if let act = items[indexPath.row] as Activity {
            if act.client != nil {
                // ...
            }
        }

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

在闭包内检索数据,因此我已将items数组声明为可选,因为它在第一次运行时可能为零.

我收到错误'[AnyObject]?' 在这一行没有名为'subscript'的成员if let act = items[indexPath.row] as? Activity.

我无法弄清楚如何解决这个问题.

Ant*_*nio 21

该数组声明为:

 private var items: [AnyObject]?
Run Code Online (Sandbox Code Playgroud)

所以,正如你所说,它是可选的

在swift中,a optional是一个枚举,所以它本身就是一个类型 - 作为一个可选类型,它可以包含nil所包含类型的值或对象.

您希望将下标应用于数组,而不是应用于可选项,因此在使用它之前,您必须从可选项中解包该数组

items?[indexPath.row]
Run Code Online (Sandbox Code Playgroud)

但这还不是全部 - 你还必须使用条件下转:

as? Activity
Run Code Online (Sandbox Code Playgroud)

因为前面的表达式可以评估为nil

所以编写if语句的正确方法是

if let act = items?[indexPath.row] as? Activity {
Run Code Online (Sandbox Code Playgroud)