Search code examples
swiftuikitlogical-operators

Not logical operator


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


Solution

    • "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 want 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 that 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 that 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.