Learn

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 Integers and Doubles, 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

1.

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 if tuneSquadPoints is less than monstarsPoints using the correct comparison operator.

  • Within the body of your if statement, print a message for the winning team.

2.

Add an else statement. Within the body of your else statement, print a message for the other winning team.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?