How to correct avoid this force cast

Viewed 2896

I have this force cast:

let cell = tableView.dequeueReusableCell(withIdentifier: "TownTableViewCell",
                                                     for: indexPath) as! TownTableViewCell

And trying to avoid this by typical method:

if let cell = tableView.dequeueReusableCell(withIdentifier: "TownTableViewCell",
                                                     for: indexPath){
} 

But its not correct, how should i solve this?

5 Answers

Don't avoid it, do the force cast.

That's one of the rare cases where a force cast is welcome.

The code must not crash if everything is hooked up correctly. If it does it reveals a design mistake.

Avoiding the force cast with optional binding is pointless because in case of the mentioned design mistake the table view will display nothing.

You can use guard.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
guard let viewCell = cell as? ImageCollectionViewCell else {
    return YourCollectionViewCell()
}
return viewCell

good luck

Related