Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSIndexPath and IndexPath in Swift 3.0

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.

like image 546
PGDev Avatar asked Sep 22 '16 06:09

PGDev


People also ask

What is NSIndexPath in Swift?

An object containing a list of indexes that bridges to IndexPath ; use NSIndexPath when you need reference semantics or other Foundation-specific behavior.

What is IndexPath in Tableview Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.

How does Swift compare to IndexPath?

The Swift overlay to the Foundation framework provides the IndexPath structure, which bridges to the NSIndexPath class. This means that, as an alternative to NSIndexPath , starting with Swift 3 and Xcode 8, you can use IndexPath . Note that IndexPath also conforms to Equatable protocol. Therefore, you can use == or !=

What is IndexPath Uitableview?

IndexPath contains information about which row in which section the function is asking about. Base on this numbers you are configuring the cell to display the data for given row.


1 Answers

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.

like image 159
Martin R Avatar answered Sep 27 '22 18:09

Martin R