Conditional Control Flow

Discover how to write Swift control flow logic to decide which lines of code should be executed and which should not. In addition, practice using the conditional control flow constructs provided by Swift.

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 ...