ios - .IsEmpty 返回 False

标签 ios swift indexoutofboundsexception

我正在使用以下代码检查数组是否为空,然后为 tableview 返回 0 行数以避免崩溃。但即使数组为空,它也不会返回 0 行计数并进入它不应该做的其他部分。因此,我的应用程序因索引超出范围异常而崩溃。

我尝试使用 countisEmpty 进行两次检查,但即使数组为空,它仍然进入 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.categoryDe​​tail.isEmpty 因为你之前检查过 HomeVC.categoryDe​​tail.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。因为可以自动完成从UIntInt。计数 已经作为 Int 返回。

注3:使用? : 用于一行两个条件的情况。它将阻止您使用额外的代码和未定义的状态。

所以代码是:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return HomeVC.categoryDetail.isEmpty ? 0 : HomeVC.categoryDetail.count + 3
}

注意 4:在 return 之前尝试 print(HomeVC.categoryDe​​tail) 以查看当您期望为空时里面有什么,但实际上不是.

关于ios - .IsEmpty 返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799932/

相关文章:

ios - 使用 Sprite Kit 将尺寸从 4 英寸调整为 3.5

swift - 在 Swift 中将字节附加到 NSMutableData

Java ArrayList 抛出 IndexOutOfBoundsException。为什么?

java - ArrayIndexOutOfBoundsException : 2 >= 1 on for each

objective-c - 同一 NSManagedObject 之间的多种关系

ios - MPNowPlayingInfoCenter - 当音频暂停时耗时继续计数

ios - 使平移手势需要所有 4 个滑动手势都失败

ios - UITableView 具有表格及其单元格的动态高度

swift - 未在集合上计算的计算属性

c++ - 数组索引循环开始而不是内存访问错误