So far, our conditions have consisted of a single variable whose value is a Boolean, true
or false
. With the help of operators, we can expand on this and create conditions that utilize multiple values to achieve a Boolean result.
In this exercise, weโll learn about one particular group of operators in Swift known as comparison operators. Comparison operators determine the relationship between two operands and return a Boolean value as a result.
Swift supports the following comparison operators:
==
Equal to!=
Not Equal to>
Greater than<
Less than>=
Greater than or equal to<=
Less than or equal to
Comparison operators are most commonly used to compare numerical values such as Integer
s and Double
s, though ==
and !=
can also be used to compare String
values.
4 < 5 // true 0.5 > 0.1 // true 3.5 <= 3.0 // false 12 >= 15 // false "A" == "A" // true "B" != "b" // true
Notice how a capital "B"
is not equal to a lowercase "b"
since Swift is a case sensitive language.
Combining our knowledge of if/else
statements and comparison operators, we can construct the following conditional to check for a studentโs grade on an exam:
let grade = 95 if grade > 65 { print("You passed!") } else { print("You failed.") }
Since the studentโs grade
is greater than 65
, the first code block gets executed and prints, You passed!
๐.
Instructions
In SwiftJam.swift, weโll set up an if
/else
statement that determines the winning team in a basketball game between tuneSquad and Monstars.
First, create an
if
statement that checks iftuneSquadPoints
is less thanmonstarsPoints
using the correct comparison operator.Within the body of your
if
statement, print a message for the winning team.
Add an else
statement. Within the body of your else
statement, print a message for the other winning team.