iosswiftuitableview

Is there a way to not return a cell after a condition in UITableView?


I am working with a UITableView and want to add a conditional statement inside the cellForRowAt function to decide whether or not I should return a cell.

Here's an example of what I mean:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  // Here is where I add the code to calculate which cells should appear, though it's not important for this example

  if  condition {
    return cell
  } 
}

But the error message I get is Missing return in a function expected to return 'UITableViewCell'

Is there a way I can not return something?


Solution

  • I am afraid that the only acceptable solution is to do that:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        // Here is where I add the code to calculate which cells should appear, though it's not important for this example
    
        if condition {
            return cell
        } 
    
        // return empty cell
        return UITableViewCell()
    }