Swift - Equal To and Not Equal To

Introduction

To check for the equality of two variables, use the equal to == operator.

The == operator works with numbers as well as strings. Consider the following example:

Demo

var n = 6
if n % 2 == 1 {/*from   w  w w  . j a v  a 2  s .c o m*/
    print("Odd number")
} else {
    print("Even number")
}

Result

The preceding code checks whether the remainder of a number divided by two is equal to one.

If it is, then the number is an odd number, otherwise it is an even number.

The following example shows the == operator comparing string values:

Demo

var status = "ready"
if status == "ready" {
    print("Machine is ready")
} else {/*from w ww .j  a  v  a  2 s  .  c  o m*/
    print("Machine is not ready")
}

Result

Besides the == operator, you can use the not equal to != operator.

The following code shows the earlier example rewritten using the != operator:

Demo

var n = 6
if n % 2 != 1 {//  w ww.j a v a  2  s . c  o m
    print("Even number")
} else {
    print("Odd number")
}

Result

You can use the != operator for string comparisons:

Demo

var status = "ready"
if status != "ready" {
    print("not ready")
} else {//from w w w .  j  ava2 s. c  o m
    print("ready")
}

Result

The == and != operators also work with Character types:

Demo

let char1:Character = "A"
let char2:Character = "B"
let char3:Character = "B"
print(char1 == char2) //false
print(char2 == char3) //true
print(char1 != char2) //true
print(char2 != char3) //false

Result

When comparing instances of classes, you need to use the identity operators === and !==

Related Topic