Reputation: 239
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?
Upvotes: 0
Views: 759
Reputation: 124
I know this is an old post, but I ran into this same issue and thought I'd share my solution. I used the same code that Mohanad Refaai posted above:
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()
}
But I didn't like the empty cell in the UITableView, so I made it's height zero:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if condition {
return 0
}
return 52
}
I hope this helps.
Upvotes: 0
Reputation: 347
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()
}
Upvotes: 2
Reputation: 9612
Is there a way I can not return something?
Even though this is not a best practice - yes, you can silence this Xcode compile-time error message by using a fatal error:
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
}
fatalError()
}
But in case if for some reason condition
is false - the app will crash, so be aware of that.
In order to get more context from fatal error - you can pass a string to it describing what has happened, e.g:
fatalError("Condition Is Invalid, Failed Returning a Cell")
Upvotes: 1
Reputation: 17844
No, you need to always return a cell.
If you need to suppress cells, better do so in the data source methods, like numberOfRowsInSection
.
Upvotes: 0