Search code examples
swiftxcodeswift3

How to correct avoid this force cast


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?


Solution

  • 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.