我正在使用以下代码检查数组是否为空,然后为 tableview 返回 0 行数以避免崩溃。但即使数组为空,它也不会返回 0 行计数并进入它不应该做的其他部分。因此,我的应用程序因索引超出范围异常而崩溃。
我尝试使用 count
和 isEmpty
进行两次检查,但即使数组为空,它仍然进入 else 部分。
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if HomeVC.categoryDetail.count == 0{
return 0
}else{
if(HomeVC.categoryDetail.isEmpty)
{
return 0
}
else
{
return HomeVC.categoryDetail.count + 3 as Int
}
}
}
我要保证在数组没有值的时候不进入else部分。
最佳答案
你不会的。实际上你永远不会到达 HomeVC.categoryDetail.isEmpty
因为你之前检查过 HomeVC.categoryDetail.count == 0
。
注意 1:通常 .isEmpty
比获取 .count
性能更高。因为当你只检查最后一个索引时,不需要计算项目。
Count Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection. - Source
注意 2:不需要将 count
转换为 Int
。因为可以自动完成从UInt
到Int
。计数 已经作为 Int
返回。
注3:使用? :
用于一行两个条件的情况。它将阻止您使用额外的代码和未定义的状态。
所以代码是:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return HomeVC.categoryDetail.isEmpty ? 0 : HomeVC.categoryDetail.count + 3
}
注意 4:在 return
之前尝试 print(HomeVC.categoryDetail)
以查看当您期望为空时里面有什么,但实际上不是.
关于ios - .IsEmpty 返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799932/