How to check if IndexPath is valid?

╄→尐↘猪︶ㄣ 提交于 2019-12-03 15:27:28

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

Usually you can consider an indexPath invalid if it represents a row where there is no corresponding data in the data source. (One exception would be "Load more" rows.)

If you really need to create an invalid IndexPath, you can do:

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

After the update:

self.tableView.indexPathForSelectedRow returns an Optional so can be nil if there is no selected row.

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

Anyway, comparing path against NSNotFound raises an exception in all cases.

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

import UIKit

extension UITableView {

    func hasRowAtIndexPath(indexPath: NSIndexPath) -> 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 as NSIndexPath) {
    // do something
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!