brightec
Home Services Projects Blog About Contact

Control Flow Statements - If/Guard | Swift Basics

Swift basics 001

There are many control flow statements in Swift, far too many to cover in 1 post. Here we'll just briefly look at the if and guard statements.

If

A standard feature of any programming language, a normal if statement in swift doesn't need parentheses for the condition but does require braces around the statements.

if condition {

}

A common usage of if in Swift is to check whether an optional variable is nil, and unwrap it if it isn't:

if let variable = variable {
 // variable is non-optional here
}

Guard

A nice feature of swift is the guard statement. It's like an if statement with only an else block. The else block must terminate execution of the current scope (i.e. return or throw).

guard condition else {
 return
}

guard let variable = variable else {
 return
}

These are commonly used within functions as part of the golden path/early return pattern, allowing you to validate your input at the top of a function and leave the primary code (the golden path) nicely grouped together at the bottom of the function.

The benefits of a guard statement over an if statement include:

  • Your condition can more often be written positively e.g. guard condition else { return } vs if !condition { return }
  • You can't forget the return statement e.g.
// This will compile
if !success {
 callback(false)
}
// This won't compile
guard success else {
 callback(false)
}

Pattern matching - Enumeration Case

Enumeration Case pattern matching is most commonly seen in switch statements however it's also possible to use them in an if/guard statement. Take the following enum and variable:

enum Result {
 case success
 case failure
}
let result: Result = .success

With these, the following switch and if statement are equivalent:

switch result {
case .success:
 // code here is executed
case .failure:
 break
}

if case .success = result {
 // code here is executed
}

See how the case .success from the switch forms the left-hand side of the condition and result (the variable being switched on) is the right-hand side of the condition. While the if statement has the advantage of being shorter, it could be argued that the switch is clearer, especially if this is the first time you've seen if case in a code base.

You should also consider how you want your code to behave if another case is added to the enum. If your switch is explicit as it is above (i.e. doesn't have a default case), adding another case to the enum would cause a compiler error on the switch. This can help to stop bugs from being introduced into your code. The same can't be said for the if statement which would continue to compile.


Looking for something else?

Search over 200 blog posts from our team

Want to hear more?

Subscribe to our monthly digest of blogs to stay in the loop and come with us on our journey to make things better!