0

Is there any difference between these statements, or can they be used as per developer preference?

!myValue.isEmpty

vs.

myValue.isEmpty == false

Curious to understand how they differ from a compiler point of view.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Chaya
  • 21
  • 8
  • 2
    While using "== false" may be more obvious, I'd say using "!" is more common, as it's more compact, and it's consistent with the opposite "value.isEmpty". "value.isEmpty == true" is a bit redundant/unnecessary. – Ernie Thomason Aug 12 '20 at 23:45

1 Answers1

3

! is a logical NOT operator.

This reverses the Boolean value:

!value.isEmpty

== is a comparison operator.

This compares the bool value against another:

value.isEmpty == false

For Boolean variables both produce the same result.


Assuming value.isEmpty is false:

!value.isEmpty translates to !false which translates to true

value.isEmpty == false translates to false == false which translates to true

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 2
    To add onto this, `==` checks if the two values/objects are the same, while `===` checks if the two objects share the same reference. More info about this [here](https://stackoverflow.com/questions/24002819/difference-between-and) – SunnyChopper Aug 12 '20 at 23:36
  • 1
    so yes these are logically equivalent – TMin Aug 12 '20 at 23:36
  • @pawello2222 performance wise, does it make any difference ? – Chaya Aug 12 '20 at 23:56
  • 1
    @Chaya No, it doesn't. It's just a matter of preference. You can take a look at [this thread](https://softwareengineering.stackexchange.com/questions/136908/why-use-boolean-variable-over-boolean-variable-false) – pawello2222 Aug 13 '20 at 00:00
  • @pawello2222 Great! this is what i was looking for. – Chaya Aug 13 '20 at 00:11
  • 5
    @Chaya you might need to use `== false` and `== true` if you have an optional `Bool` because in this situation you would have a third possibility `== nil` – Leo Dabus Aug 13 '20 at 00:24