Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.

ForceCast

Since: PMD 7.0

Priority: Medium (3)

Force casts should be avoided. This may lead to a crash if it’s not used carefully. For example assuming a JSON property has a given type, or your reused Cell has a certain contract. Consider using conditional casting and handling the resulting optional.

This rule is defined by the following XPath expression:

//TypeCastingOperator[T-as and T-bang]

Example(s):

NSNumber() as! Int // violation, force casting

NSNumber() as? Int // no violation

Use this rule by referencing it:

<rule ref="category/swift/errorprone.xml/ForceCast" />

ForceTry

Since: PMD 7.0

Priority: Medium (3)

Force tries should be avoided. If the code being wrapped happens to raise and exception, our application will crash. Consider using a conditional try and handling the resulting optional, or wrapping the try statement in a do-catch block.

This rule is defined by the following XPath expression:

//TryOperator[T-bang]

Example(s):

let x = try! someThrowingFunction() // violation, force trying

let x = try? someThrowingFunction() // no violation

Use this rule by referencing it:

<rule ref="category/swift/errorprone.xml/ForceTry" />