How to check if IndexPath is valid?

Lirik picture Lirik · Apr 25, 2017 · Viewed 7.1k times · Source

Prior to swift 3, i used to use for example:

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

But now, since i use IndexPath class in swift3, i'm looking for the equivalent for the path != NSNotFound check.

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

Answer

pableiros picture pableiros · Apr 25, 2017

To check if IndexPath exists, I use this extension function:

import UIKit

extension UITableView {

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

And to use it I do something like this:

if tableView.hasRowAtIndexPath(indexPath: indexPath) {
    // do something
}