Compare Two Numbers
To compare two numbers in Swift, use Relational operators like equal to, greater than, less than, etc.
If Two Numbers are Equal
To check if two numbers are equal, use equal to ==
operator.
main.swift
import Foundation
var a = 4
var b = 4
if (a == b) {
print("a and b are equal.")
} else {
print("a and b are not equal.")
}
Program Output
a and b are equal.
If a Number is Greater than the Other
To check if a number is greater than the other number, use greater than >
operator.
main.swift
import Foundation
var a = 8
var b = 4
if (a > b) {
print("a is greater than b.")
} else {
print("a is not greater than b.")
}
Program Output
a is greater than b.
If a Number is Less than the Other
To check if a number is less than the other number, use less than <
operator.
main.swift
import Foundation
var a = 2
var b = 4
if (a < b) {
print("a is less than b.")
} else {
print("a is not less than b.")
}
Program Output
a is less than b.
Compare Numbers
Now, let us combine all these three scenarios of equal to, greater than and less than.
main.swift
import Foundation
var a = 8
var b = 4
if (a == b) {
print("a and b are equal.")
} else if (a > b) {
print("a is greater than b.")
} else {
print("a is less than b.")
}
Program Output
a is greater than b.
Summary
Summarising this tutorial, we have learnt that to compare two numbers, use relational operators.