The guard statement provides similar functionality to the if
statement, but is intended for use in situations where you want to do an early bailout of the current scope if one or more con‐ ditions are not met.
The basic structure of the guard statement in a function is
as follows:
func someFunc() {
guard condition else { return // exit function
}
// continue execution // ...
}
In this example, return was used to exit the function. Other
statements that end the current scope can be used in other con‐ texts, such as break or continue.
Optional binding (see “Optionals” on page 81) can be used as part of the condition, in which case the bound values are avail‐ able for the remainder of the guard statement’s scope.
The following example shows a loop that processes an array of strings to see which can be interpreted as integers:
var input = ["45", "27", "Apple", "3"] for str in input {
guard let ageAsInt = Int(str) else { // not an int, so ignore continue
}
print ("age:", ageAsInt) }
• Generally in functions, use guard-let rather than if-let
to ensure an optional holds a value.
• The guard statement can include an optional where
condition clause. Both conditions must be true in order
for the guard statement to not execute the else clause.
• If using optional binding (as in guard-let), you can use
compound conditions—multiple comma-separated bind‐ ing let assignments that must all resolve to non-nil val‐
ues in order for the guard statement to not execute
the else clause.
As with if-case, guard can take a case pattern match instead of
a condition, and can include enumeration values, let variable
binding, and a where clause. See “for-in variations” on page
90 for related information and examples.
switch
The switch statement provides an alternative (and more con‐
cise) way to express a series of condition (or pattern) tests, which you might otherwise implement by using a chain of if- else statements.
The basic structure of the statement is as follows:
switch expression { case pattern1: // statements to execute case pattern2: // statements to execute case patternN: // statements to execute default: // statements to execute }
The expression is evaluated, and the result is compared to each
of the patterns associated with each case clause. If a match is
found, the statements that form part of the matching case are executed. If no match is found, the statements that follow the optional default clause are executed.
A pattern may contain a single value or a series of values sepa‐ rated by commas, as shown here:
case 2, 4, 6:
The switch statement in Swift is considerably enhanced com‐
pared to its counterpart in C-like languages. Here are the nota‐ ble differences:
• The case clauses must be exhaustive (all possible values
of expression must match a cast pattern, or there must
be a default case to catch those that aren’t); otherwise,
the compiler will report an error.
• Execution of statements attached to a case clause will not
fall through into another case unless this behavior is
prevents a common error in C, where a break statement
may have been accidentally omitted).
• Every case must contain at least one executable statement.
• If more than one case pattern matches, the first matching case is the one that is used.
• A single case can test for a match against a range of
values.
• You can use tuples to test multiple values in a single
case pattern.
• The case clause can use an optional where clause to fur‐
ther refine the case match (see the section “The where qualifier” on page 100).
• The break statement is not required to prevent fall-
through into the next case, but you can use it as a “no- operation” statement to terminate a case and continue execution at the next statement after the switch state‐ ment. This is useful when you need to match a specific case and exclude it ahead of another more general case that would otherwise include it.
Here is a simple example of a switch statement with multiple
cases:
var a = "c" switch a {
case "a", "e", "i", "o", "u": print("this letter is a vowel") case "b", "d", "g", "k", "p", "t":
print("this letter may be a plosive sound in " + "English")
fallthrough
case "c", "f", "h", "j", "l", "m", "n", "q", "r", "s", "v", "w", "x", "y", "z":
print("this letter is a consonant") default:
print("this character doesn't interest me") }
Let’s analyze this example a little closer:
• If a pattern match is made in the first case clause, a mes‐
sage is printed indicating the letter is a vowel, and execu‐ tion continues at the next statement after the switch
statement.
• If a pattern match is found in the second case clause, the print() function is called, but the fallthrough keyword
causes execution to continue into the statement(s) defined as part of the next case clause (in this example, a
second print() function is called).