Problematic `== true/false` boolean comparisons

There are situations where this is reasonable when you have something other than a boolean literal on both sides of the ==. For example, here’s some code to count how many contiguous runs of identical values there are in an array of booleans:

func countGroups(values: [Bool]) -> Int {
    var groupCount = 0
    var prevValue: Bool? = nil

    for curVal in values {
        if curVal != prevValue {  // Comparing Bool to Bool?
            groupCount += 1       // Always count first one, no matter the value!
        }
        prevValue = curVal
    }

    return groupCount
}

(Yes, there are other ways to code this; yes, it could be generic; yes, it’s a silly little toy problem. But there are more realistic contexts where that same “compare to optional previous” pattern might show up and be desirable.)

I could see emitting a warning when one side of an == is a boolean literal, not just a boolean expression — but that feels to me more like a job for SwiftLint than for the compiler.

4 Likes