Swift

Swift

Made by DeepSource

Force casts should be avoided SW-W1013

Bug risk
Major

Casting is a way to convert an instance of one type to another. Swift's type system is designed to be safe, and casts can lead to unexpected errors if done incorrectly.

Why is this an issue: Forced casts are a potential source of runtime crashes, and can be difficult to debug. They can also lead to unexpected behavior, as the cast may not succeed as expected. This can cause a ripple effect throughout your codebase, making it difficult to find and fix the root cause of the issue. How to fix the issue: Instead of using a forced cast, use conditional casting (as?) and optional binding to safely unwrap and work with the result. This allows you to handle the case where the cast fails, and avoid runtime crashes. Alternatively, consider refactoring your code to avoid the need for casting altogether. If you find yourself needing to cast frequently, it may be a sign that your code could benefit from a better design.

Bad Practice

let view = self.view as! MyCustomView
view.doSomething()

Recommended

if let view = self.view as? MyCustomView {
    view.doSomething()
} else {
    // handle the case where the cast fails
}