我正在将核心数据数据库中的对象列表加载到表视图中。
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]?” 在此行没有名为'subscript'的成员if let act = items[indexPath.row] as? Activity
。
我不知道如何解决这个问题。
该数组声明为:
private var items: [AnyObject]?
所以,正如您还说的,这是可选的
swift中的anoptional
是一个枚举,因此是一个类型本身-并且作为可选的类型,它可以包含nil
值或包含类型的对象。
您希望将下标应用于数组,而不是可选数组,因此在使用下标之前,必须先将数组与可选数组解包
items?[indexPath.row]
但这还不是全部-您还必须使用条件下调:
as? Activity
因为先前的表达式可以计算为nil
所以写if语句的正确方法是
if let act = items?[indexPath.row] as? Activity {
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句