Here is an example of guard clauses from the notes:
The previous example is standard but not very good. Let's see another one:
return
or throw
The Swift language has a guard statement:
If the condition is true
, processing after the guard statement continues. If the condition is false
, then the else
is executed. Note that the else
must contain a return
or throw
. The scope of the variable extends outside of the guard statement and is in scope throughout the rest of the block the guard statement is in.
The guard statement was added in Swift 2.0. A more typical usage is declaring variables with the let
statement that are optionals (which map nicely to nullable pointers):
where the Swift language class DataManager
maps to this Objective-C:
Note that Objective-C is a superset of the C language, so it has pointers. NSString
is the standard string class.
Before Swift 2.0, without the _guard statement*, it required you to:
This is even more noticeable when there are multiple levels of optionals:
This was why Swift 2.0 added the guard statement: