Conditional Control Flow
Explore how to implement conditional control flow in Swift using if, else, else if statements, and the guard statement. Understand decision-making processes in programming to control which code runs based on true or false conditions.
We'll cover the following...
In a previous lesson, we looked at how to use logical expressions in Swift to determine whether something is true or false. Since programming is largely an exercise in applying logic, much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed and, conversely, which code gets by-passed when the program is executing.
Using the if statement
The if statement is perhaps the most basic of control flow options available to the Swift programmer. Programmers who are familiar with C, Objective-C, C++, or Java will immediately be comfortable using Swift if statements.
The basic syntax of the Swift if statement is as follows:
if boolean expression {
// Swift code to be executed when the expression evaluates to true
}
Unlike some other programming languages, it is important to note that the braces ({}) are mandatory in Swift, even if only one line of code is executed after the if expression.
Essentially, if the Boolean expression evaluates to true, then the code in the body of the statement is executed. The body of the statement is enclosed in ...