3.4. Comparison Operators (and Booleans)
Swift uses many comparison operators like, ==, !=, <, >, and so on. We use the following operators the most:
==
Equal to
a == b
is a equal to b?
!=
Not equal to
a != b
is a not equal to b?
<
Less than
a < b
is a less than b?
>
Greater than
a > b
is a greater than b?
<=
Less than or equal to
a <= b
is a less than or equal to b?
>=
Greater than or equal to
a >= b
is a greater than or equal to b?
Booleans:
Boolean is a very important data type in any programming language, and it's no different for Swift. Booleans can only have two values: true, and false. We can create a boolean variable in Swift by writing the following:
// Either with type annotations
var myBool: Bool = false
// Or without type annotations
var yourBool = true Booleans are very closely related to Comparison Operators. For example, let's look into the following code:
// Comparison operators and Booleans...
let a = 10
let b = 12
let isEqual = a == b
print(isEqual)
print(type(of: isEqual))It prints:
It means a==b is comparing a with b to check if a is equal to b,and returning the decision in boolean. Since the decision is not true, it creates the constant isEqual with the value false.
Comparison operators are widely used in Conditionals, Loops, and many other places where we make binary decisions.
Last updated
Was this helpful?