3

I know what guard does in Swift. I have read the questions about using guard or if let. However, is there any difference between guard (condition) else { return } and if !condition { return }? They seem to do the same thing.

EDIT: This was not asking about guard let and if let. I now know that guard let is a more useful usage of guard. I was simply asking about the differences between a simple guard and if.

Derek Kaplan
  • 138
  • 9

2 Answers2

2

There is a difference if you need to declare a variable in the guard statement, i.e.

guard let foo = bar else { return }

In this case, you can continue to use foo as a non-optional in the rest of the method. You can't do this with a simple if statement.

If you're wondering why that's handy:

if let because = nobody {
    if let likes = pyramids {
        if let of = doom {
            // guard can help you avoid this!
        }
    }
}
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
  • You can avoid that with if let also. The key difference when unwrapping optionals like this is which scope they are declared in. Also... `if let because = nobody, let likes = using, indentation == pyramids {}` – Fogmeister Aug 11 '17 at 21:02
  • 1
    In this simplified case, yes. In real code, the "if let" statements may be long enough that cramming them all into one giant line with commas ends up being quite ugly. You might also have other code in between, as in: `guard let foo = getFoo() else { return } bar() guard let baz = getBaz() else { return } ` etc. – Charles Srstka Aug 11 '17 at 21:05
  • why use one giant line? Put new lines between each statement. But the same is true when binding optionals using guard let too so really a moot point. – Fogmeister Aug 11 '17 at 21:06
  • See the edit to my comment (marred by the lack of support for newlines in the comment, but hopefully still comprehensible). – Charles Srstka Aug 11 '17 at 21:08
  • For example, a common use for guard is to bail out in case of errors. In this case, the guards will be sprinkled throughout a method, not necessarily all clustered in one place. – Charles Srstka Aug 11 '17 at 21:08
  • yes. I know what guard is used for. In the example in your answer it is no different between using guard or if. – Fogmeister Aug 11 '17 at 21:09
  • It's a simplified example. The point should be clear; you can declare variables that might be optional without introducing a new scope. – Charles Srstka Aug 11 '17 at 21:12
0

They will achieve the same affect.

For readability sake, having a guard statement at the top of your method lets people know that this value has to be here to continue. Its very easy to spot as opposed to an if statement

temp
  • 639
  • 1
  • 8
  • 22