Is force cast really bad and should always avoid it?

前端 未结 7 1325
无人及你
无人及你 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:42

    In cases where you are really sure the object should be of the specified type it would be OK to down cast. However, I use the following global function in those cases to get a more meaningful result in the logs which is in my eyes a better approach:

    public func castSafely(_ object: Any, expectedType: T.Type) -> T {
        guard let typedObject = object as? T else {
            fatalError("Expected object: \(object) to be of type: \(expectedType)")
        }
        return typedObject
    }
    

    Example usage:

    class AnalysisViewController: UIViewController {
    
        var analysisView: AnalysisView {
            return castSafely(self.view, expectedType: AnalysisView.self)
        }
    
        override func loadView() {
            view = AnalysisView()
        }
    }
    

提交回复
热议问题