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
.
An object containing a list of indexes that bridges to IndexPath ; use NSIndexPath when you need reference semantics or other Foundation-specific behavior.
indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.
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 !=
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With