Rule: “Code Smell: Remove the unnecessary Boolean literal. ([swift:S1125])” does not work properly with optionals in Swift.
Sample code:
var optBool: Bool? = true
if optBool == true {/* ... */ }
SonarCloud gives a warning for this code and the suggestion in the description in S1125 is to write if optBool
instead. However, this is not allowed for optional booleans in Swift.
An alternative writing that actually compiles could be:
var optBool: Bool? = true
if (optBool ?? false) {/* ... */ }
or:
var optBool: Bool? = true
if let optBool, optBool {/* ... */ }
While opinions may vary, I personally don’t perceive any of these alternatives as being more readable than if optBool == true
. Therefore, I believe it is not correct to label this as a code smell.
Obviously, the same applies when checking for false: if optBool == false
should not be reported as a code smell either