.IsEmpty returns 假
.IsEmpty returns False
我正在使用以下代码检查数组是否为空,然后 return tableview 的行数为 0 以避免崩溃。但即使数组为空,它也不会 returning 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)
以查看当您期望为空时里面是什么,但实际上不是。
我正在使用以下代码检查数组是否为空,然后 return tableview 的行数为 0 以避免崩溃。但即使数组为空,它也不会 returning 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)
以查看当您期望为空时里面是什么,但实际上不是。