NSIndexPath and IndexPath in Swift 3.0

19,383

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

which you can access directly:

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

Apparently the Xcode migrator did not a perfect job.

Share:
19,383
PGDev
Author by

PGDev

Hi

Updated on June 18, 2022

Comments

  • PGDev
    PGDev about 2 years

    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
        }
    

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

  • Mark Dail
    Mark Dail almost 6 years
    The reason to convert is if you are sending the IndexPath to a function that requires a NSIndexPath as an argument, or at least you need to in Swift 4.