Home > Blockchain >  Not logical operator
Not logical operator

Time:02-17

I need help to understand the following codes. Why does it print "yes" even if !test is equal to true. Thanks


var test: Bool = false

if !test  {
    print("yes")
}

if !test == true  {
    print("oky")
}

print(!test)


Console:

yes
oky
true

CodePudding user response:

  • "test" variable is defined with default value 'false'.
  • "if !test" is equal to "if !test == true", in both case your test is negated that means 'false' become 'true' and that's why your prints are executed.

I would just like to add that there are developers for whom the negative logic is hard to read. Below are some examples of such logical expressions.

examples of logic which takes time to process:

  • view.isHidden = !isLoading
  • view.isHidden = !hasData
  • view.isHidden = !canAdd
  • view.idHidden = !(data?.isEmpty ?? true)
  • view.isHidden = !hasChanges

possible solutions are:

  • create "isVisible" on view
  • use if else

There is a great article which threats the subject in depth:

Don’t ever not avoid negative logic

If you want to be nice to people with a challenged relationship with boolean logic, try to avoid negative formulations and negations.

CodePudding user response:

test equals false, as defined in your first line.

The not operator (!) returns true if the statement is false, and false if the statement is true.

Since test equals false, !test equals true.

The two conditions if (!test) and if (!test == true) are both met since !test is true, so the text is printed.

CodePudding user response:

Because if the condition after if is true, the commands get executed.

These lines are equivalent:

if !test  {

if !test == true  {

I think you might be confusing the value of test with the value of !test. The Not operator negates the value of whatever it acts upon, in this case the variable test.

  • Related