Confused with the NOT operator when used in if-statements?

850 views Asked by At
func nonZeroAnswer (a : Double, b : Double) -> Bool {

       if a / b == 0 { return true}  else {return false}
 }

nonZeroAnswer (5, 0)   //This returns false

if !nonZeroAnswer(2, 2) {
     print("This is a Zero Answer")
}

I've read the apple documentation over and over and know how the Not operator works and how it inverts a boolean value to its opposite but I don't know how to apply it in more complex code scenarios such as if statements, functions, etc. I don't even know if I wrote this basic program correctly, I'm all in all confused on how to go about writing such a basic program. I'm sorry if this seems like a petty question but I've read the apple documentation and also am studying a swift book that is supposedly for beginners, I've watched numerous youtube videos but just can't wrap my head around using the Not operator in different scenarios other than the ordinary trueValue = True ........ !trueValue //makes it false......That I do understand but furthermore just gets confusing like in this program I've attempted to write above.

2

There are 2 answers

0
Sergey Kalinichenko On

Boolean expressions, with and without ! operator, remain the same when you use them in the context of a control statement, such as if, while, etc. The only difference is what the control statement does based on the result of the evaluation.

One way to reason about Boolean expressions is to consider them independently of their context. For example, you could look at the expression

!nonZeroAnswer(2, 2)

and see that it is true when nonZeroAnswer(2, 2) is false, and vice versa. After that you could "plug in" the result into the if or the while, or whatever the context may be, and say, for example, that

if !nonZeroAnswer(2, 2) {
     print("This is a Zero Answer")
}

prints something when nonZeroAnswer(2, 2) returns false.

Note : Instead of writing a conditional that returns true or false, you could return the Boolean expression itself, because it has the same value:

func nonZeroAnswer (a : Double, b : Double) -> Bool {
    return a / b == 0
}

a / b == 0 is already a Boolean expression that returns true when dividing a by b produces zero, so there is no need to put an if conditional around it.

0
Abhishek729 On

Its basic coding. ! symbol just inverts the boolean value Consider following 2 scenarios:-

nonZeroAnswer(2,2)  
//returns false as (2/2 = 1) != 0
//Hence !nonZeroAnswer(2,2) = !false = true
//Hence "This is a zero answer" will be printed in this case as the condition for if block is true

nonZeroAnswer(0,3)
//returns true as (0/3 = 0) == 0
//Hence !nonZeroAnswer(0,3) = !true = false
//Hence "This is a zero answer" will not be printed as the condition for if block is false. So wont enter the block.