If NOT Conditional case in Swift

In this tutorial, we will learn If NOT conditional case in Swift.

We usually do a lot of conditional statements like If else… or if else if…

These types of conditional statements generally check if a condition is True or not. On the basis of that it executes a block of code within the brackets.

But have you ever wondered what to do if you want to run a piece of code if a condition is not True.

Well, this tutorial will guide you to run a conditional statement if the condition is only false without using else.

We can say this an “If not”.

Syntax

if !(your condition is here) {
 //Your code that you want to be executed here
}

We just need to use !this as NOT.

An example of if not in Swift

Here is a simple example.

let number1 = 10
if !(number1 < 8) {
    print("This is If NOT")
}

Output:

This is If NOT

If we use ! this symbol before our condition then the program will check if the condition is false or not. If the condition is false then only it will execute the code written in the curly brackets.

Fix error: unary operator cannot be separated from its operand

Note:

Make sure your condition is within these brackets () otherwise it won’t work. For example, if you do this

let number1 = 10
if ! number1 < 8 {
    print("This is If NOT")
}

You will get an output like this:

error: unary operator cannot be separated from its operand.

To fix this you just need to do this: if !(number1 < 8)

Also read: Functions in Swift

Leave a Reply

Your email address will not be published.