Comparison operators (==, !=, >, <, >=, <=)
Comparison operators return a Bool
to indicate whether or not a given statement is true. They are used heavily in if statements.
- Equal to
==
- Not equal to
!=
- Greater than
>
- Less than
<
- Greater than or equal to
>=
- Less than or equal to
<=
- Comparing equality of two struct instances
- Comparing equality of two class instances
- Further reading
Equal to ==
print(5 + 5 == 10) // true
print(1 + 1 == 11) // false
Not equal to !=
print(5 + 5 != 10) // false
print(1 + 1 != 11) // true
Greater than >
print(5 > 10) // false
print(10 > 2) // true
Less than <
print(5 < 10) // true
print(10 < 2) // false
Greater than or equal to >=
print(10 >= 10) // true
print(15 >= 16) // false
print(18 >= 12) // true
Less than or equal to <=
print(10 <= 10) // true
print(15 <= 16) // true
print(18 <= 12) // false
Comparing equality of two struct instances
The ==
and !=
may also be used to check to see if two struct instances have the same values. For this, the struct must conform to Equatable
.
struct Player: Equatable {
var name: String
var score: Int
}
let player1 = Player(name: "Tomoko", score: 100)
let player2 = Player(name: "Tomoko", score: 100)
let player3 = Player(name: "Isabella", score: 350)
let player4 = player1
print(player1 == player2) // true
print(player1 == player3) // false
print(player1 == player4) // true
print(player1 != player2) // false
print(player1 != player3) // true
print(player1 != player4) // false
Comparing equality of two class instances
The ==
and !=
may also be used to check to see if two class instances have the same values. For this, the class must also conform to Equatable
, which involves more work than if it was a struct.
class Player: Equatable {
var name: String
var score: Int
init(name: String, score: Int) {
self.name = name
self.score = score
}
static func == (lhs: Player, rhs: Player) -> Bool {
return lhs.name == rhs.name && lhs.score == rhs.score
}
}
let player1 = Player(name: "Tomoko", score: 100)
let player2 = Player(name: "Tomoko", score: 100)
let player3 = Player(name: "Isabella", score: 350)
let player4 = player1
print(player1 == player2) // true
print(player1 == player3) // false
print(player1 == player4) // true
print(player1 != player2) // false
print(player1 != player3) // true
print(player1 != player4) // false
Note: While ==
and !=
compare class instance equality, ===
and !==
compare identity, which is a similar, but different concept.