Comparison operators compare two values of the same type and return a Bool value (true or false).
If you try to compare values of different types, the compiler produces an error.
The standard comparison operators in Swift are:
| Operator | Description | Example |
|---|---|---|
== |
Equal to |
1 == 1 (true) |
!= |
Not equal to |
1 != 2 (true) |
< |
Less than |
4 < 5 (true) |
<= |
Less than or equal to |
4 <= 4 (true) |
> |
Greater than |
3 > 1 (true) |
>= |
Greater than or equal to |
2 >= 2 (true) |
A conditional statement executes code based on whether a condition evaluates to true or false.
The most common conditional is an if statement, which runs a block of code only when its condition is true.
Write an if statement using the if keyword, followed by the condition and the code block enclosed in curly braces:
let wheelCount = 4
if wheelCount == 4 {
print("Your vehicle is a car")
}
// Prints "Your vehicle is a car"
You can pair if with an else clause to run alternative code when the condition is false:
let precipitationInMM = 0.5
if precipitationInMM > 0.5 {
print("You will need an umbrella")
} else {
print("You will not need an umbrella")
}
// Prints "You will not need an umbrella"
To test multiple conditions in sequence, chain statements together using else if.
An if statement does not require an else branch, but you can include one to handle cases when none of the conditions match:
let favoriteFruit = "Apple"
if favoriteFruit == "Banana" {
print("Your favorite fruit is a banana")
} else if favoriteFruit == "Orange" {
print("Your favorite fruit is an orange")
} else if favoriteFruit == "Apple" {
print("Your favorite fruit is an apple")
} else {
print("Your favorite fruit is not a banana, orange, or apple")
}
// Prints "Your favorite fruit is an apple"
In modern Swift, if statements can also be used as expressions that produce a value.
Each branch evaluates to a value, making it easy to assign results conditionally:
let cpuBits = 32
let architecture = if cpuBits == 64 {
"x86_64"
} else {
"x86_32"
}
print(architecture)
// Prints "x86_32"
The ternary conditional operator is a concise shorthand for an if-else expression.
It evaluates a condition and returns one of two values depending on whether that condition is true or false.
The operator uses three parts: condition ? trueExpression : falseExpression.
If condition evaluates to true, trueExpression is evaluated and returned; otherwise, falseExpression is evaluated and returned.
The ternary operator is ideal for simple, one-line choices:
let showFahrenheit = true
let temperatureInCelsius = 30
let temperature = showFahrenheit ? temperatureInCelsius * 9 / 5 + 32 : temperatureInCelsius
print(temperature)
// Prints 86
The example above is a compact equivalent to:
let showFahrenheit = true
let temperatureInCelsius = 30
let temperature = if showFahrenheit {
temperatureInCelsius * 9 / 5 + 32
} else {
temperatureInCelsius
}
In this exercise, you will write some code to help you prepare to buy a vehicle.
You have three tasks, one to determine if you will need one to help you choose between two vehicles, determine which license you will need and one to estimate the acceptable price for a used vehicle.
The auto dealers in your town are all running a five year, 0% interest promotion that you would like to take advantage of. But you are not sure if you can afford the monthly payments on the car you want.
The monthly payment is the cars total price divided by the number of months under the five year period.
Implement the canIBuy(vehicle:price:monthlyBudget:) function that takes the following arguments:
vehicle - The name of the vehicle you want to buy.price - The price of the vehicle you want to buy.monthlyBudget - The amount of money you can afford to pay each month.The function should return the following message based on the following conditions:
"Yes! I'm getting a <vehicle>"."I'll have to be frugal if I want a <vehicle>"."Darn! No <vehicle> for me".canIBuy(vehicle: "1974 Ford Pinto", price: 516.32, monthlyBudget: 100.00)
// returns "Yes! I'm getting a 1974 Ford Pinto"
canIBuy(vehicle: "2011 Bugatti Veyron", price: 2_250_880.00, monthlyBudget: 10000.00)
// returns "Darn! No 2011 Bugatti Veyron for me"
canIBuy(vehicle: "2020 Indian FTR 1200", price: 12_500, monthlyBudget: 200)
// returns "I'll have to be frugal if I want a 2020 Indian FTR 1200"
You have decided to buy a used vehicle and you need to determine what type of drivers license you will need to operate it.
Implement the licenseType(numberOfWheels:) function that takes the argument numberOfWheels which is the number of wheels on the vehicle you want to buy.
The function should return the following message based on the following conditions:
"You will need a motorcycle license for your vehicle"."You will need an automobile license for your vehicle"."You will need a commercial trucking license for your vehicle"."We do not issue licenses for those types of vehicles".licenseType(numberOfWheels: 2)
// returns "You will need a motorcycle license for your vehicle"
licenseType(numberOfWheels: 6)
// returns "You will need an automobile license for your vehicle"
licenseType(numberOfWheels: 18)
// returns "You will need a commercial trucking license for your vehicle"
licenseType(numberOfWheels: 0)
// returns "We do not issue licenses for those types of vehicles"
Now that you made your decision you want to make sure you get a fair price at the dealership. Since you are interested in buying a used vehicle, the price depends on how old the vehicle is. For a rough estimate, assume if the vehicle is less than 3 years old, it costs 80% of the original price it had when it was brand new. If it is at least 10 years old, it costs 50%. If the vehicle is at least 3 years old but not older than 10 years, it costs 70% of the original price.
Implement the calculateResellPrice(originalPrice:yearsOld:) function that takes the arguments originalPrice which holds the vehicles original price, and yearsOld which holds the age of the vehicle in years.
The function should return the resell price of the vehicle.
calculateResellPrice(originalPrice: 1000, yearsOld: 1)
// returns 800
calculateResellPrice(originalPrice: 1000, yearsOld: 5)
// returns 700
calculateResellPrice(originalPrice: 1000, yearsOld: 15)
// returns 500
Sign up to Exercism to learn and master Swift with 35 concepts116 exercises, and real human mentoring, all for free.