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:
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") }
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:
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") }
Besides the == operator, you can use the not equal to != operator.
The following code shows the earlier example rewritten using the != operator:
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") }
You can use the != operator for string comparisons:
var status = "ready" if status != "ready" { print("not ready") } else {//from w w w . j ava2 s. c o m print("ready") }
The == and != operators also work with Character types:
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
When comparing instances of classes, you need to use the identity operators === and !==