moosgrn
moosgrn

Reputation: 379

Return Empty Cell to Avoid Force Casting TableView?

I'm using "as!" for a custom tableView cell and my understanding is that it's generally OK, however I'm using SwiftLint and would like to see if I can provide an alternative. Using a guard statement, is there an alternative I can provide that won't cause a crash? Or should I go a different route? Thanks!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as? CustomTableViewCell
         else {
            return //something?
    } 

Upvotes: 0

Views: 373

Answers (2)

vadian
vadian

Reputation: 285069

There is no alternative. Force unwrap the cell! That's one of the rare cases where force unwrapping is fine.

The code must not crash if the class of the cell and its identifier is set correctly.

I doubt the usefulness of those tools which only distinguish between black and white.

Returning something like a generic cell couldn't be a solution because it causes bad user experience, too.

Upvotes: 1

Maci
Maci

Reputation: 123

You could return a UITableViewCell with one of the styles UIKit provides for you.

For example UITableViewCell(style: .default, reuseIdentifier: "YourReuseIdentifier").

Upvotes: 1

Related Questions