'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 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jan |
| Solution 2 | vpprof |
