7

I am confused about when to use guard and when to use if...else.

Is guard is replacement or alternative for If statement ? Main thing want to know what are the functional benefits of guard statement for Swift language?

Any help to clear this situation will be appreciated.

technerd
  • 14,144
  • 10
  • 61
  • 92
  • 6
    Does [this prior Q&A](http://stackoverflow.com/questions/30791488/swift-2-guard-keyword) answer your question? – Marc Khadpe Jan 10 '16 at 07:46

1 Answers1

18

Using guard might not seem much different to using if, but with guard your intention is clearer: execution should not continue if your conditions are not met. Plus it has the advantage of being shorter and more readable, so guard is a real improvement, and I'm sure it will be adopted quickly.

There is one bonus to using guard that might make it even more useful to you: if you use it to unwrap any optionals, those unwrapped values stay around for you to use in the rest of your code block. For example:

   guard let unwrappedName = userName else {
return
}

print("Your username is \(unwrappedName)")

This is in comparison to a straight if statement, where the unwrapped value would be available only inside the if block, like this:

if let unwrappedName = userName {
print("Your username is \(unwrappedName)")
} else {
return
}

// this won't work – unwrappedName doesn't exist here!
print("Your username is \(unwrappedName)")

https://www.hackingwithswift.com/swift2

Muhammad Saifullah
  • 4,292
  • 1
  • 29
  • 59
  • Second point for Unwrapped value scope is clear for me, but still not get How early return perform by guard statement when we have to check multiple conditions. – technerd Jan 11 '16 at 06:24