Swift 3.0中的NSIndexPath和IndexPath

17

我最近将我的代码转换为Swift 3.0。现在,我的集合视图和表格视图数据源方法中,方法签名包含IndexPath而不是NSIndexPath。但是,在方法定义内部仍然需要将IndexPath强制类型转换为NSIndexPath。即,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell : NNAmenitiesOrFurnishingCollectionViewCell = self.amenitiesOrFurnishingCollectionView.dequeueReusableCell(withReuseIdentifier: "NNAmenitiesOrFurnishingCollectionViewCell", for: indexPath) as! NNAmenitiesOrFurnishingCollectionViewCell
        cell.facilityImageName = self.facilityArray[(indexPath as NSIndexPath).row].imageName
        cell.facilityLabelString = self.facilityArray[(indexPath as NSIndexPath).row].labelText
        return cell
    }

有人能告诉我为什么要将 indexPath 强制转换为 NSIndexPath 类型吗?

1个回答

27

这里没有必要将 IndexPath 转换为 NSIndexPath。 Swift 3的覆盖类型 IndexPath 具有属性。

/// The section of this index path, when used with `UITableView`.
///
/// - precondition: The index path must have exactly two elements.
public var section: Int

/// The row of this index path, when used with `UITableView`.
///
/// - precondition: The index path must have exactly two elements.
public var row: Int

您可以直接访问:

    cell.facilityImageName = self.facilityArray[indexPath.row].imageName
    cell.facilityLabelString = self.facilityArray[indexPath.row].labelText

显然,Xcode迁移工具并没有完美地完成工作。


2
转换的原因是如果您将IndexPath发送到需要NSIndexPath作为参数的函数中,或者至少在Swift 4中需要这样做。 - Mark Dail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接