我正在将核心数据数据库中的对象列表加载到 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/