涉及 indexPath 和 NSIndexPath 的代码有效——但为什么它是多余的?

code involving indexPath & NSIndexPath works - but why is it redundant?

我将重新开始使用 CloudKit,在我重新访问的项目中,我执行了查询提取,并留下了一组 CKRecords。我将此数组设置为通过 TableController 显示。无论如何,我有这一行代码(有效)......但我不确定为什么我将 indexPath 设置为 NSIndexPath。

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "dining") as! table1cell
    let restaurant: CKRecord = categories[(indexPath as NSIndexPath).row]
    cell.Name.text = restaurant.value(forKey: "Name") as? String

    return cell

对于我的其他非 CKRecord TableController 项目,我知道我本质上不必将 indexPath 设置为其自身。我在这里错过了什么?

如果 indexPath 未存储在显式类型化的 var 中,您可能会强制转换它以避免出现编译器消息。如果编译器不知道 indexPath 是 NSIndexPath 类型,访问 .row 属性 可能会导致错误。

你在哪里 declaring/storing indexPath?当您删除 as NSIndexPath 转换时会发生什么?

编辑:重新阅读你的问题,我相信答案是:

"You are not storing indexPath as itself, you are casting whatever is stored in indexPath to be of type NSIndexPath"

使用转换为 NSIndexPath 是没有意义的。只需将行更改为:

let restaurant: CKRecord = categories[indexPath.row]