ios - [AnyObject] ?' does not have a member named ' 下标'

标签 ios arrays swift option-type

我正在将核心数据数据库中的对象列表加载到 TableView 中。

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

数据是在闭包内检索的,所以我将 items 数组声明为可选数组,因为它在第一次运行时可能为 nil。

我遇到错误'[AnyObject]?'在此行 if let act = items[indexPath.row] as? 没有名为 'subscript' 的成员?事件

我不知道如何解决这个问题。

最佳答案

数组声明为:

 private var items: [AnyObject]?

所以,正如你所说,这是一个可选的

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

你想将下标应用于数组,而不是可选的,所以在使用它之前你必须从可选中解包数组

items?[indexPath.row]

但这还不是全部——您还必须使用条件向下转换:

as? Activity

因为前面的表达式可以求值为nil

所以if语句的正确写法是

if let act = items?[indexPath.row] as? Activity {

关于ios - [AnyObject] ?' does not have a member named ' 下标',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25975489/

相关文章:

ios - 为什么我的程序总是说 "unrecognised selector sent to instance"?

arrays - 在 3d 矩阵的第二维中排序

php - 基本的PHP MySQL数组分组问题

java - 为什么此代码显示一个空数组列表,即使我在请求期间向其中添加了元素?

ios - 在 plist 字符串中添加变量

ios - 如何以编程方式快速创建 uicollectionview(没有 Storyboard)

ios - 有没有办法在iOS中将蒙版图像转换为UIBezierPath

ios - NSOperationQueue 中类的对象 - 使用委托(delegate)的异步方法

ios - MKMapView 在 iPhone 5c 中离开 View Controller 后挂起/卡住应用程序

swift - UITextField 在输入之前显示 "Optional("")"