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.
Boolean expressions, with and without
!
operator, remain the same when you use them in the context of a control statement, such asif
,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
and see that it is
true
whennonZeroAnswer(2, 2)
isfalse
, and vice versa. After that you could "plug in" the result into theif
or thewhile
, or whatever the context may be, and say, for example, thatprints something when
nonZeroAnswer(2, 2)
returnsfalse
.Note : Instead of writing a conditional that returns
true
orfalse
, you could return the Boolean expression itself, because it has the same value:a / b == 0
is already a Boolean expression that returnstrue
when dividinga
byb
produces zero, so there is no need to put anif
conditional around it.