# Problematic \`== true/false\` boolean comparisons

**URL:** <https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314>\
**Category:** Discussion\
**Tags:** optionals, bool\
**Created:** [January 20, 2025, 4:05pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314 "2025-01-20T16:05:32Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexhunsley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexhunsley/32/31344_2.png) [@alexhunsley](https://forums.swift.org/u/alexhunsley)\
**Post date:** [January 20, 2025, 4:05pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/1 "2025-01-20T16:05:32Z")

</div>

# Intro

This isn't an evolution proposal; it's my research on what feels like a weird snaggy bit around bool comparisons in Swift involving three-value logic. The snag makes it too easy to write fragile or incorrect code.

I'm interested in ways to make this fragile code harder to write, or at least have it signposted better when you're doing it (warnings etc).

This has been discussed before, see forum links at end.

# The issue

Swift has extensions/code for `==` that allow comparison of `Optional<Bool>` with `Bool`, essentially sneaking in a kind of three-value logic. Not sure of the historical reasons for this, but it allows various mistakes and fragile code to be created without any compiler warning.

Example: in order to check if an optional string has data -- in which we need it to be non-nil and `.isEmpty == false` -- we would idiomatically write:

```swift
let str: String? = ...
if let str, !str.isEmpty {

```

However, I've seen this being done and even promoted as 'nicer' code:

```swift
if str?.isEmpty == false {

```

This works as per desired behaviour, but it's not good code; it's fragile. For example, someone might come along later and want to code the opposite check ("it's nil or `.isEmpty == true`"), and quite understandably might just flip the boolean:

```swift
if str?.isEmpty == true {

```

This is not actually the opposite check -- it's buggy, it will regard `nil` as containing data (because neither `true` nor `false` are equal to `nil`).

So IMO there's too much cognitive load to reason about/change this code, and you're expected to know `false != nil` to fully understand it.  
(Note also that if someone flipped the code by changing the check to `!= false` instead of `== true`, it would be a correct change! Which is very counter-intuitive.)

Here's another example of broken code I've seen in the wild: it's supposed to be guarding against an array having `true` at the end:

```swift
let bools: [Bool] = []
guard bools.last == false else {
    print("Error: last bool in array is true")
}

```

So `.last` returns an optional, and `nil != false`, so if array is empty we enter the guard.  
(And there's no compiler warning for the code above.)

# Bool comparisons considered harmful?

Thought:

Is there ever an actual need to write `== true` or `== false` in Swift? It's not idiomatic, and crucially the ability to do so allows the sorts of fragility detailed above to happen.

# Things that might help

Sometimes people like explicit bool checks for clarity (even though it's not idiomatic) -- in those cases, extension on `Bool` could provide `.isTrue` and `.isFalse` (and no handling implemented for `Optional<Bool>`).

SwiftLint has a rule to warn you off creating option Bool properties ([discouraged\_optional\_boolean Reference](https://realm.github.io/SwiftLint/discouraged_optional_boolean.html)). This is only heading off one possible cause of the issue though; optional chaining and funcs that return optional bool (e.g. `[Bool].last`) can still introduce opportunity for the problem without any compiler warning AFAICS.

We can write a specialisation on `==` that generates a warning, at least:

```swift
@available(*, deprecated, message: "Comparing Optional<Boolean> using == is not safe practice. Unwrap the value and use direct expression evaluation e.g. 'if boolExpression' or 'if !boolExpression'")
func == (lhs: Bool?, rhs: Bool) -> Bool {
    guard let unwrappedLHS = lhs else { return false }
    return unwrappedLHS == rhs
}
// (not shown: other two variants for `Bool, Bool?` and `Bool?, Bool?`)

```

and this code does generate compiler warnings for me for these two problem cases:

```swift
let strings: [String] = []
if strings.last?.isEmpty == false { }

let str: String? = nil
if str?.isEmpty == false { }

```

# Links

There have been a few related proposal for SwiftLint rules that never panned out:

- [Rule Request: Discourage comparing Bool value with `true` or `false` · Issue #3420 · realm/SwiftLint · GitHub](https://github.com/realm/SwiftLint/issues/3420)
- [Rule request: No explicit `== true` or `== false` · Issue #1502 · realm/SwiftLint · GitHub](https://github.com/realm/SwiftLint/issues/1502)

Related forum posts:

- [The Optional Truth](https://forums.swift.org/t/the-optional-truth/13965)
- [Boolean comparison causes extremely slow compilation](https://forums.swift.org/t/boolean-comparison-causes-extremely-slow-compilation/41609) -- another reason to avoid explicit boolean comparisons

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [January 20, 2025, 5:16pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/2 "2025-01-20T17:16:25Z")

</div>

> [@alexhunsley](#):
>
> Is there ever an actual need to write `== true` or `== false` in Swift?

FWIW, I do consider this an anti-pattern in Swift, and in all languages that don’t use a fuzzy notion of “truthiness” for conditionals. Even in languages like JS, Python, and Ruby that accept non-boolean values as `if` conditions, it’s definitely a code smell.

`== true` / `== false` is a habit we specifically attempt to train out of students at Macalester. One little data point, but it’s something.

None of that is really an answer to the language safety question, but it does suggest we’re at least somewhat more in the realm of “the language doesn’t stop you from writing bad code” than in the realm of “the language exhibits unreasonable behavior for reasonable code.”

---

<div class="post-metadata">

**Author:** ![alexhunsley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexhunsley/32/31344_2.png) [@alexhunsley](https://forums.swift.org/u/alexhunsley)\
**Post date:** [January 20, 2025, 5:25pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/3 "2025-01-20T17:25:17Z")

</div>

Thanks Paul. I agree on it being an anti pattern, I always call out == true/false in reviews.

And as you note, the logic here of Swift is indeed internally consistent; it’s more that it “gives you enough rope” so to speak.

If I saw some of the code samples above in a project (e.g. the .last example) I’d be thinking “does the author know what the behaviour is and they intended this? Or is this a booby trap in waiting?”

Maybe it would be useful for compiler to emit a warning when you’re explicitly comparing booleans and optional Booleans, which my == specialisation gives a sketch of doing.

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [January 20, 2025, 6:35pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/4 "2025-01-20T18:35:58Z")

</div>

> [@alexhunsley](#):
>
> Maybe it would be useful for compiler to emit a warning when you’re explicitly comparing booleans and optional Booleans

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:

```swift
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.

---

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [January 20, 2025, 7:51pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/6 "2025-01-20T19:51:49Z")

</div>

> [@alexhunsley](#):
>
> `if str?.isEmpty == false { }`

I think compiler might produce a warning in such code along with quick fix using `if-let` to address this.

For instance, string interpolation has warning for optionals, encouraging dealing with it there. The case presented here is probably even more error-prone and better be addressed via compiler.

As for explicit boolean comparison, for `false` there are justification on improved readability against exclamation mark, so discouraging this way of writing doesn’t seem appealing to me.

---

<div class="post-metadata">

**Author:** ![bbrk24](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bbrk24/32/27370_2.png) [@bbrk24](https://forums.swift.org/u/bbrk24)\
**Post date:** [January 20, 2025, 8:25pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/7 "2025-01-20T20:25:37Z")

</div>

I've also seen `!= true` to permit both `false` and `nil`; what would be the expected workaround for that?

---

<div class="post-metadata">

**Author:** ![ksluder](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@ksluder](https://forums.swift.org/u/ksluder)\
**Post date:** [January 20, 2025, 9:12pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/8 "2025-01-20T21:12:48Z")

</div>

I think the answer is “don’t do that”—use `if foo == nil || !foo {` instead.

---

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [January 20, 2025, 10:27pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/9 "2025-01-20T22:27:37Z")

</div>

Alternatively, `if !(foo ?? false)`

---

<div class="post-metadata">

**Author:** ![davedelong](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davedelong/32/38708_2.png) [@davedelong](https://forums.swift.org/u/davedelong)\
**Post date:** [January 20, 2025, 10:54pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/11 "2025-01-20T22:54:00Z")

</div>

IMO, `!= true` is _fine_. The point of the code is to make sense to the reader. The compiler doesn't care either way. Sometimes it may make sense to do `(optBool ?? false) == false`. Sometimes it might feel better to do `optBool != true`.

Go with what most clearly expresses the intent of the code, and if it's still not clear enough to you, add comments explaining what's going on and why.

---

<div class="post-metadata">

**Author:** ![bbrk24](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bbrk24/32/27370_2.png) [@bbrk24](https://forums.swift.org/u/bbrk24)\
**Post date:** [January 21, 2025, 3:31am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/13 "2025-01-21T03:31:49Z")

</div>

> [@ksluder](#):
>
> `if foo == nil || !foo {`

This isn’t valid because `foo` is still of type `Bool?` on the RHS of the `||`.

> [@davedelong](#):
>
> `(optBool ?? false) == false`

Fair, I’ve seen this before.

---

<div class="post-metadata">

**Author:** ![ksluder](https://avatars.discourse-cdn.com/v4/letter/k/eada6e/32.png) [@ksluder](https://forums.swift.org/u/ksluder)\
**Post date:** [January 21, 2025, 3:37am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/14 "2025-01-21T03:37:57Z")

</div>

> [@bbrk24](#):
>
> This isn’t valid because `foo` is still of type `Bool?` on the RHS of the `||`.

Yes, my mistake. You can write this as `if foo == nil || !(foo!) {`, but `if !(foo ?? false) {` is easier to understand. You might also be able to do `guard let foo, foo else { return }` depending on context.

I believe this situation motivated someone to ask for an `unless` keyword (edit: or `ifn't` if you’re @Joe_Groff), but ultimately how often does one actually test for an optional Boolean being nil or false without also handling the case where it’s true?

---

<div class="post-metadata">

**Author:** ![ibex](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ibex/32/30439_2.png) [@ibex](https://forums.swift.org/u/ibex)\
**Post date:** [January 21, 2025, 4:15am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/15 "2025-01-21T04:15:16Z")

</div>

> [@itaiferber](#):
>
> Alternatively, `if !(foo ?? false)`

Sorry, that looks cute but I have found it really hard to parse mentally.

> [@bbrk24](#):
>
> > [@davedelong](#):
> >
> > `(optBool ?? false) == false`
> 
> Fair, I’ve seen this before

Ditto.

`Short writing makes long reading.` 🙂

```swift
if let foo {
   // was set
   ...
}
else {
   // fuzzy
   // was not even set
   ...
}

```

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [January 21, 2025, 9:27am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/16 "2025-01-21T09:27:30Z")

</div>

> [@bbrk24](#):
>
> I've also seen `!= true` to permit both `false` and `nil`; what would be the expected workaround for that?

```swift
let someOptionalBool: Bool? = ...

switch someOptionalBool {
  case nil, false:
    // value is nil or false
  case true:
    // value is true
}

```

When there are three possible values, why not switch over all possible values?

---

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [January 21, 2025, 11:33am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/18 "2025-01-21T11:33:30Z")

</div>

> [@Danny](#):
>
> That is not exhaustive. You need to unwrap.

I’m surprised `case nil, false?, true?` is considered exhaustive, but `case nil, false, true` is not. That feels like it should be a bug.

> [@Danny](#):
>
> To use this only for an if statement looks quite terrible, I think.

There’s no need to use the switch statement for an if statement’s condition — switch is already a branching construct.

---

<div class="post-metadata">

**Author:** ![tevelee](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tevelee/32/9775_2.png) [@tevelee](https://forums.swift.org/u/tevelee)\
**Post date:** [January 21, 2025, 12:24pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/19 "2025-01-21T12:24:19Z")

</div>

I think your initial expression is pretty idiomatic.

> [@alexhunsley](#):
>
> `if let str, !str.isEmpty {`

For complex ones I usually resort to using map/flatMap on Optionals:

```swift
if strings.last.map({ !$0.isEmpty }) ?? false {

```

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [January 21, 2025, 1:14pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/20 "2025-01-21T13:14:54Z")

</div>

> [@Danny](#):
>
> That is not exhaustive. You need to unwrap.

It is. But sure, you can be explicit and use `true?` or `.some(true)` instead of just `true`. However, they all [match the same case](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/patterns/#Enumeration-Case-Pattern).

> [@](#):
>
> To use this only for an if statement looks quite terrible, I think.

Agreed, but why would you do that?! You'd certainly want to place the code that would go in the if-branch, inside the switch, non?

---

<div class="post-metadata">

**Author:** ![phoneyDev](https://avatars.discourse-cdn.com/v4/letter/p/49beb7/32.png) [@phoneyDev](https://forums.swift.org/u/phoneyDev)\
**Post date:** [January 22, 2025, 12:26am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/22 "2025-01-22T00:26:21Z")

</div>

I've used `isNilOrEmpty` quite a bit.

```swift
extension Optional where Wrapped == String {
    public var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

```

I think they use this a lot in Java. It could conceivably be in the Swift Standard Library.

---

<div class="post-metadata">

**Author:** ![sspringer](https://avatars.discourse-cdn.com/v4/letter/s/e9c0ed/32.png) [@sspringer](https://forums.swift.org/u/sspringer)\
**Post date:** [January 22, 2025, 8:54am UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/24 "2025-01-22T08:54:36Z")

</div>

I warning should not be emitted for code that many might see as a valid option, be it for terseness. Also do not introduce constructs that are actually harder to grasp. The problem is (in the boolean case) that you have to fit the four cases `== true`, `!= true`, `== false`, and `!= false` (which all make sense in certain situations) into one easy syntax, I guess this is hard to achieve.

There might be a good syntax for a _subset_ of those cases, e.g.

`if optionalValue?.isEmpty? { … }` meaning ` if let optionalValue?.isEmpty == true`

So `if !optionalValue?.isEmpty? { … }` would mean `if optionalValue?.isEmpty != true { … }`.

> [@phoneyDev](#):
>
> I've used `isNilOrEmpty` quite a bit.

Instead of `if optionalValue.isNilOrEmpty { … }`:

`if !optionalValue?.!isEmpty? { … }`

Hmm. Let‘s see if people have fun with _that_ 😉

---

<div class="post-metadata">

**Author:** ![alexhunsley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexhunsley/32/31344_2.png) [@alexhunsley](https://forums.swift.org/u/alexhunsley)\
**Post date:** [January 23, 2025, 4:51pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/25 "2025-01-23T16:51:52Z")

</div>

I actually coded something like this recently - `isEmptyNil` I called it (for code completion purposes) -- and added a marker protocol `Emptyness` and then conformed all the things with `.isEmpty` to that protocol (Data, String, Collections, etc).

```swift
protocol Emptyness {
    var isEmpty: Bool { get }
}

extension Optional where Wrapped: Emptyness {
    var isEmptyNil: Bool {
        switch self {
        case .none:
            true
        case let .some(wrapped):
            wrapped.isEmpty
        }
    }
    var hasData: Bool { !isEmptyNil }
}

/// Swift API conformances to Emptyness
extension String: Emptyness {}
extension Array: Emptyness {}
extension ArraySlice: Emptyness {}
extension Set: Emptyness {}
extension Dictionary: Emptyness {}
extension Data: Emptyness {}
extension Range: Emptyness {}
extension ClosedRange: Emptyness {}
extension Substring: Emptyness {}
extension UnsafeBufferPointer: Emptyness {}

protocol Collection: Emptyness {}
protocol Sequence: Emptyness {}

```

(And it contains `.hasData` for reverse of `.isEmpty`. Not strictly necessary of course, but can be useful to tidy up some expressions.)

---

<div class="post-metadata">

**Author:** ![alexhunsley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexhunsley/32/31344_2.png) [@alexhunsley](https://forums.swift.org/u/alexhunsley)\
**Post date:** [January 23, 2025, 5:04pm UTC](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314/28 "2025-01-23T17:04:19Z")

</div>

> [@Danny](#):
>
> It would not make sense\* to require `.some` for `Bool` but not all other `Equatable` types.
> 
> ```swift
> let bool: _? = Bool.random()
> #expect(bool == .some(true))
> 
> let int: _? = Int.random(in: 0...2)
> #expect(int == 1)
> 
> ```
> 
> - Edit: Maybe that's not true. Seems worthy of discussion; it's not immediately obvious to me exactly what makes `Bool` a problem, but it does seem somewhat special in this regard. I think it's something like, "`Optional` promotion can make people think `Bool?`'s `==` only needs to consider two values, when the real number is three".

Yeah, I think the fundamental issue obviously isn't just Bool, but any type that has finite possible states (enums, most typically). The fewer states, the more likely a reader is to fall into the "it's not A or B, therefore it must be C" kind of thinking.

But Bool _is_ kind of special, given its fundamental importance in the language around checking booleans expressions or values.

[Next page](https://forums.swift.org/t/problematic-true-false-boolean-comparisons/77314.md?page=2)
