Swift-style-guide: if vs guard

Created on 25 Oct 2018  ·  3Comments  ·  Source: raywenderlich/swift-style-guide

The current style guide is clear regarding using guard instead of nesting if, but it could show an example when if should be used instead of guard, aka where there is no unwrapping of optionals needed:

Preferred:

if !success { return false }

Not preferred:

guard success else { return false }

Best described here: https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

Most helpful comment

I would almost say that the Failing Guards section covers this:
Guard statements are required to exit in some way.

...or as Natasha's blog put it:
think of guard as a lightweight Assert

You should therefore do:

guard success else { return false }

The benefit of the guard here is that the compiler will guarantee the exit. Example:

// This compiles fine and a bug risks going unnoticed
if !success {
  // Some code here
  // Forgot the return statement
}

// Compiler error, you are required to return and the bug is prevented
guard success else {
  // Some code here
  // Forgot the return statement
}

All 3 comments

I would almost say that the Failing Guards section covers this:
Guard statements are required to exit in some way.

...or as Natasha's blog put it:
think of guard as a lightweight Assert

You should therefore do:

guard success else { return false }

The benefit of the guard here is that the compiler will guarantee the exit. Example:

// This compiles fine and a bug risks going unnoticed
if !success {
  // Some code here
  // Forgot the return statement
}

// Compiler error, you are required to return and the bug is prevented
guard success else {
  // Some code here
  // Forgot the return statement
}

@RobertGummesson so your rule of thumb would be that - even if you don't need to unwrap optionals - you'd use guard over if if you encounter failure that requires exiting. Correct?

@agirault - Yes, either that or you simply require exiting (whether or not it's due to a failure).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  ·  26Comments

WingYn picture WingYn  ·  15Comments

samkim102 picture samkim102  ·  4Comments

rwenderlich picture rwenderlich  ·  29Comments

icanzilb picture icanzilb  ·  6Comments