如何检查IndexPath是否有效? [英] How to check if IndexPath is valid?
问题描述
在swift 3之前,我习惯使用例如:
Prior to swift 3, i used to use for example:
let path = self.tableView.indexPathForSelectedRow
if (path != NSNotFound) {
//do something
}
但是现在,因为我在swift3中使用 IndexPath
类,我正在寻找路径的等价物!= NSNotFound
检查。
But now, since i use IndexPath
class in swift3, i'm looking for the equivalent for the path != NSNotFound
check.
Xcode8.3.1编译器错误: 二元运算符'!='不能应用于'IndexPath类型的操作数'和'Int'
推荐答案
从语义上讲,要考虑indexPath 无效,你需要检查一些东西,比如表格视图或集合视图。
Semantically, to consider an indexPath invalid, you need something to check for such as a table view or a collection view.
如果 indexPath 表示数据源中没有相应数据的行,通常可以认为 indexPath 无效。 (一个例外是加载更多行。)
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.)
如果确实需要创建无效的 IndexPath
,你可以这样做:
If you really need to create an invalid IndexPath
, you can do:
let invalidIndexPath = IndexPath(row: NSNotFound, section: NSNotFound)
更新后:
self.tableView.indexPathForSelectedRow
返回一个Optional,如果没有选定的行,可以 nil
。
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.
}
无论如何,比较路径
针对 NSNotFound
在所有情况下都会引发异常。
Anyway, comparing path
against NSNotFound
raises an exception in all cases.
这篇关于如何检查IndexPath是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!