Introduction to Swift | Control Statements | Conditional Branching with if
This article introduces Swift control statements. Control statements consist of conditional branches and loops. We begin with the basic conditional branch: the if statement.
If you have experience with another programming language, you probably know what an if statement does. It specifies work to perform according to a condition.
Basic form of if (1)
if condition {
... processing when the condition is true ...
}
Basic form of if (2)
if condition {
... processing when the condition is true ...
} else {
... processing when the condition is false ...
}
Write a condition after if. You can use anything that evaluates to a Boolean value, such as a value, variable, expression, function, or method. In some languages, conditions must be surrounded by parentheses. In Swift, parentheses are optional.
◯ if (x == 0) {...}
◯ if x == 0 {...}
The processing after the condition and the processing after else must be enclosed in braces ({}). Some languages allow braces to be omitted for a single statement, but Swift always requires them.
Using else if
When a condition is not satisfied, add if after else to continue checking conditions with else if.
if condition {
... processing ...
} else if condition {
... processing ...
} else if ... continue as needed ...
}
If an else if condition is not satisfied, you can add another else if condition or finish with else.