Is force cast really bad and should always avoid it?

Viewed 33609

I started to use swiftLint and noticed one of the best practices for Swift is to avoid force cast. However I used it a lot when handling tableView, collectionView for cells :

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! MyOffersViewCell

If this is not the best practice, what's the right way to handle this? I guess I can use if let with as?, but does that mean for else condition I will need to return an empty cell? Is that acceptable?

if let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as? MyOffersViewCell {
      // code
} else {
      // code
}
7 Answers

Others have written about a more general case, but I want to give my solution to this exact case:

guard let cell = tableView.dequeueReusableCell(
    withIdentifier: PropertyTableViewCell.reuseIdentifier,
    for: indexPath) as? PropertyTableViewCell
else {
    fatalError("DequeueReusableCell failed while casting")
}

Basically, wrap it around a guard statement and cast it optionally with as?.

As described in some casting discussions, forcing the cast for tableView.dequeueReusableCell is ok and can/should be done.

As answered on the Swiftlint Github site you can use a simple way to turn it off for the table cell forced cast.

Link to Swiftlink issue 145

// swiftlint:disable force_cast
let cell = tableView.dequeueReusableCell(withIdentifier: "cellOnOff", for: indexPath) as! SettingsCellOnOff
// swiftlint:enable force_cast

When you are working with your types and are sure that they have an expected type and always have values, it should force cast. If your apps crash you can easily find out you have a mistake on which part of UI, Dequeuing Cell, ...

But when you are going to cast types that you don't know that is it always the same type? Or is that always have value? You should avoid force unwrap

Like JSON that comes from a server that you aren't sure what type is that or one of that keys have value or not

Sorry for my bad English I’m trying to improve myself

Good luck

Related