How to check if IndexPath is valid?

Prior to fast 3, I used, for example, the following:

let path = self.tableView.indexPathForSelectedRow
if (path != NSNotFound) {
//do something
 }

But now, since I use the class IndexPathin swift3, I am looking for an equivalent for validation path != NSNotFound.

Xcode8.3.1 compiler error: "The binary operator '! =' Cannot be applied to operands of type IndexPath and Int

+4
source share
2 answers

Semantically, to consider indexPath invalid, you need to check something, such as a table view or a collection view.

indexPath , , . ( " ".)

IndexPath, :

let invalidIndexPath = IndexPath(row: NSNotFound, section: NSNotFound)

:

self.tableView.indexPathForSelectedRow , nil, .

if let path = tableView.indexPathForSelectedRow {
  // There is a selected row, so path is not nil.
}
else {
  // No row is selected.
}

path NSNotFound .

+9

, IndexPath, :

import UIKit

extension UITableView {

    func hasRowAtIndexPath(indexPath: NSIndexPath) -> Bool {
        return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
    }
}

, - :

if tableView.hasRowAtIndexPath(indexPath: indexPath as NSIndexPath) {
    // do something
}
+4

Source: https://habr.com/ru/post/1675622/


All Articles