iosswiftindexoutofboundsexception

.IsEmpty returns False


I am using the following code to check if the array is empty and then return 0 number of rows for tableview to avoid the crash. But even when the array is empty it is not returning 0 row count and enters the else part which it is not supposed to do. Hence my application crashes with an index out of range exception.

I have tried putting two checks using count and isEmpty but it still enters the else part even when the array is empty.

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
        }
    }
}

I want to ensure that it won't enter the else part when the array has no value.


Solution

  • You won't. Actually you never reach HomeVC.categoryDetail.isEmpty because you checked HomeVC.categoryDetail.count == 0 earlier.

    Note 1: Generally .isEmpty is much more performant than getting .count. Because there is no need to count items when you can check only the last index.

    Count Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection. - Source

    Note 2: There is no need to cast count to Int. Because it can be done automatically from UInt to Int. And count is returning as Int already.

    Note 3: Use ? : for one line two conditions situations. It will prevent you from extra codes and undefined states.

    So the code would be:

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

    Note 4: Try print(HomeVC.categoryDetail) before return to see what is inside when you expect to be empty and it's not.