Take Decisions in Swift with If Statements and Boolean Operators

To be able to do anything interesting, a Swift program needs to take decisions based on whether some condition is true or not. This is done through conditionals.

Swift has several conditionals. The most common one is the if statement, which we will cover in this article.



Architecting SwiftUI apps with MVC and MVVM

GET THE FREE BOOK NOW

Table of Contents

Check if conditions are true with if statements

The most straightforward conditional checks if a constant or variable has a specific value. This is the most basic way of validating the data that apps work with.

let account = 0
if account == 0 {
	print("Empty account!")
}

Conditions are defined with the if keyword. The == operator is called equal to and checks if the account is 0. In this case, it means that you are dealing with an empty bank account.

The code executed if the condition is true is placed between curly brackets. Nothing happens if the condition is false. You need another type of if statement to check for that.

Check if conditions are either true or false with if…else statements

The previous section showed you how to check if a particular condition is true. This doesn’t cover all of the possible scenarios out there. Sometimes you need to decide if a specific condition is false instead. 

let number = 10
if number % 2 == 0 {
	print("Even number")
} else {
	print("Odd number")
}

The above code uses the % operator to check if a given number is odd or even. The else keyword is the opposite of the if one. The code executed if the condition is false is placed between curly brackets.

This is the type of condition that you’ll work with most often. It’s so common that Swift has a shorthand for them called ternary operator, which allows you to write conditions on a single line of code.

let number = 10
number % 2 == 0 ? print("Even number") : print("Odd number")

There are also more advanced use cases of conditions when you need to implement some more complex logic. There is another type of `if` statement to handle that, which you’ll learn all about next.

Use if…else if…else statements to implement chained conditions

You already know how to handle either true or false conditions. However, sometimes these conditions are not enough if the logic becomes more complicated.

let product = "apples"
let price = 10
let items = 5
if product == "" {
	print("No product available!")
} else if items == 0 {
	print("No items available for the \(product)!")
} else if price == 0 {
	print("Free \(product) available!")
} else {
	print("Total price of the \(product) is \(items * price).")
}

The above code checks first if a specific product has a valid name and price and if there are any items available in the store. It then determines the final price that the customer has to pay for the purchased items based on the product’s price and the number of requested items.

The else if statement declares a condition that is checked if either the previous if statement or else if statement in the chain of conditions is false.The code executed if the checked condition is true is placed between curly brackets. The else block gets executed if and only if the previous else if condition is false. 

You now know all the existing types of if statements out there and when to use which one. Conditions use both comparison operators and logical operators to handle the data that apps work with, and we’ll explore both concepts in the following sections of this article. 

Make decisions about the data in your apps using comparison operators

Up to this point, you have only used the == operator to write conditions. Swift has other comparison operators that you can also use when working with conditions.

The inequality operator

let first = 10
let second = 5
var result = 0
if second != 0 {
	result = first / second
} else {
	print("Invalid number!")
}

A calculator app uses the division operator to divide two given numbers. The != operator is called not equal to and checks if second isn’t 0. This prevents your code from throwing a division by zero type of error.

The less than, and less than or equal operators

The calculator app finds the minimum value of two numbers by using other comparison operators.

let first = 10
let second = 5
var minimum = 0
if first < second {
	minimum = first
} else {
	minimum = second
}

The < operator is called less than, and it checks if first is less than second. The minimum value is first if the condition is trueand second otherwise.

You can also determine the minimum value of the numbers with the <= operator. This is called less than or.

let first = 10
let second = 5
var minimum = 0
if first <= second {
	minimum = first
} else {
	minimum = second
}

If first has the same value as second, then the minimum value between the two is first since both numbers are equal.

The greater than and greater than or equal operators

The calculator app finds the maximum value of two numbers using comparison operators.

let first = 10
let second = 5
var maximum = 0
if first > second {
	maximum = first
} else {
	maximum = second
}

The > operator is called greater than, and it checks if first is greater than second. The maximum value is first if the condition is trueand second otherwise.

You can also determine the maximum value of the numbers with the >= operator. This is called greater than or equal.

let first = 10
let second = 5
var maximum = 0
if first >= second {
	maximum = first
} else {
	maximum = second
}

If first has the same value as second, then the maximum value between the two is first since both numbers are equal.

Comparison operators are powerful but don’t cover all of the possible cases. You need to use logical operators for more complex conditions. You will learn all about these next. 

Use logical operators to combine multiple conditions in an if statement

Logical operators create complex conditions from simple ones. This enables you to write advanced logic and simplify certain types of conditions that contain only boolean values.

The not operator

let download = true
if !download {
	print("Use cache")
} else {
	print("Download in progress")
}

The ! operator is the logical not one. The resulting condition is false if the initial condition is trueand false otherwise. 

The if !download condition is the shorter version of the if download == false one because !download is true if download is false and false otherwise. So the compiler executes the if statement if download is false and the else statement otherwise.

The and operator

A weather app uses other logical operators to set both the symbol and type of its temperature.

let symbol = "°C"
let degrees = "Celsius"
if symbol == "°C" && degrees == "Celsius" {
	print("Weather app")
}
if symbol == "°F" && degrees == "Fahrenheit" {
	print("Weather app")
}

The && operator is the logical and one. The resulting condition is true if and only if both conditions are true and false otherwise.

The or operator

The weather app works with Celsius degrees and °C temperature symbols. This case is covered by the very first if statement.

The weather app also works with Fahrenheit degrees and °F temperature symbols. This case is covered by the second if statement.

let symbol = "°C"
let degrees = "Celsius"
if symbol == "°C" || symbol == "°F" {
	print("Weather app")
}
if degrees == "Celsius" || degrees == "Fahrenheit" {
	print("Weather app")
}

The || operator is the logical or one. The resulting condition is true if and only if either condition is true and false otherwise.

Operator precedence

The weather app works with °C or °F temperature symbols. The very first if statement covers this scenario.

The weather app works with either Celsius degrees or Fahrenheit degrees. The second if statement covers this scenario.

You can further combine some of the aforementioned conditions for the weather app.

let symbol = "°C"
let degrees = "Celsius"
if (symbol == "°C" && degrees == "Celsius") || (symbol == "°F" && degrees == "Fahrenheit") {
	print("Weather app")
}

The round brackets show which of the two operators has higher precedence than the other. This means that the compiler first evaluates every && condition, and then and only then does it evaluate the || condition of the if statement.

The weather app either works with Celsius degrees and °C temperature symbols or with Fahrenheit degrees and °F temperature symbols. The if statement covers this scenario.

Both && and || operators use short-circuiting techniques to evaluate conditions.

If the first condition evaluated by the && operator is false, then the resulting condition is always false no matter what. So the second condition is never evaluated.

If the first condition evaluated by the || operator is true, then the resulting condition is always true no matter what. So the second condition is never evaluated either.

Conclusions

In this article, we have seen how to take decisions in a Swift program using if statements. Decisions are everywhere in programming and will be a part of any app you write.

Decisions can be based on simple conditions or complex ones. We express simple conditions using Swift’s comparison operators and combine them into complex conditions using logical operators.

Architecting SwiftUI apps with MVC and MVVM

It's easy to make an app by throwing some code together. But without best practices and robust architecture, you soon end up with unmanageable spaghetti code. In this guide I'll show you how to properly structure SwiftUI apps.

GET THE FREE BOOK NOW

Leave a Comment