Conditional statements
A conditional statement checks a condition and executes a block of code only if the condition is true
. Swift provides both the if
and if...else
conditional statements. Let's take a look at how to use these conditional statements to execute blocks of code if a specified condition is true
.
The if statement
The if
statement will check a conditional statement and, if it is true
, it will execute the block of code. This statement takes the following format:
if condition {
block of code
}
Now, let's take a look at how to use the if
statement:
let teamOneScore = 7
let teamTwoScore = 6
if teamOneScore > teamTwoScore {
print("Team One Won")
}
In the preceding example, we begin by setting the teamOneScore
and teamTwoScore
constants. We then use the if
statement to check whether the value of teamOneScore
is greater than the value of teamTwoScore
. If the value is greater, we print Team One Won
to the console. When...