Is force cast really bad and should always avoid it?

前端 未结 7 1340
无人及你
无人及你 2020-12-13 09:11

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

7条回答
  •  余生分开走
    2020-12-13 09:51

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

提交回复
热议问题