Swift - Operator NOT operator

Introduction

The logical NOT ! operator inverts a Bool value so that true becomes false and false becomes true.

The following table shows how the NOT operator works on a value:

a!a
true false
falsetrue

Consider the following statement:

var happy = true

The variable happy is of type Bool and is set to true. To invert the value of happy, use the logical NOT operator:

The value of happy is now false. You can use the logical NOT operator in an If condition, like the following:

if !happy {
    print("hi!")
}

The preceding reads: "If NOT happy, then print the line ..."

Because the value of happy is false , the NOT operator negates it and returns a true value, which satisfies the If condition.

Therefore, the line is printed.

Related Topic