本文介绍了Swift 3.0 中的 NSIndexPath 和 IndexPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have recently converted my code to Swift 3.0. My collection view and table view data source methods now contain IndexPath instead of NSIndexPath in their method signature. But still inside the method definition it is type casting IndexPath to NSIndexPath. i.e.

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.

Can anyone tell me why indexPath is type casted to NSIndexPath.

推荐答案

这里没有理由将 IndexPath 转换为 NSIndexPath.Swift 3 覆盖类型 IndexPath 具有属性

There is no reason to cast IndexPath to NSIndexPath here.The Swift 3 overlay type IndexPath has properties

/// 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 迁移器的工作并不完美.

Apparently the Xcode migrator did not a perfect job.

这篇关于Swift 3.0 中的 NSIndexPath 和 IndexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 08:42