Swift Guard vs if let cheat sheet (Swift 4)

When to use Guard:

  1. If you want to execute branching code when the unwrapping fails rather than when it succeeds.
  2. If you have to halt execution in the current enclosing scope if a value is incorrect or nil.
  3. When you need to know/want to log which optional didn’t have the correct value.
  4. If there’s potential to unwrap multiple optionals in the enclosing scope.
  5. If there’s potential that the number of optionals needed to be unwrapped can change.
  6. If you want the resulting unwrapped value to be available for the remainder of the scope and not just within a branching scope.

When to use if let

  1. Want to execute branching code when the unwrapping succeeds rather than when it fails.
  2. When you can continue execution in the current enclosing scope if a value is incorrect or nil.
  3. Don’t care which values are nil or incorrect within the enclosing scope.
  4. If you only need to unwrap a small number of optionals and that number won’t change (avoid the pyramid of doom).
  5. If you only need the unwrapped value within a branching scope.

Side Notes:

  1. Don’t forget you can also validate the resulting unwrapped optionals using multi-clause conditions.

You can also unwrap multiple optionals using this syntax as well. (Edit: Thanks to Pavel for pointing out that this syntax has replaced the where statement previously available in Swift, and thanks to Ben for pointing out a syntax error).

Notes:

  1. I wrote this after reading some different articles on the web about guard vs if let and thought it might be useful to summarize those ideas here as a TL;DR. If you want more in depth information and code examples check out this article on medium.
  2. I use the terminology “value” in the above lists but it should be noted that you can also unwrap reference types as well.

iOS Engineer @ Twitch