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.
A guard statement is as simple as using an if..else statement and has its own benefits and uses. Swift guard is defined as a statement that is used to transfer program control out of a scope if one or more conditions aren’t met.
In an if-else statement, either the if section or the else section is executed and there is no way for anything* that happens in the if section to ever transfer control to the else section (or vice versa). This statement is used for processing of mutually-exclusive code paths. What is an example of an if/else statement?
If the expression in the if statement is true, then the statement inside the if block will execute. Else the statement of the else block executes. The number is less than 50. Therefore, the else block executes. At the end of the else block, the control is passed to the next statement after the else block.
if vs if else: The if statement is a decision-making structure that consists of an expression followed by one or more statements. The if else is a decision-making structure in which the if statement can be followed by an optional else statement that executes when the expression is false. Execution
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With