Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is basic difference between guard statement and if...else statement? [duplicate]

Tags:

swift

swift2

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.

like image 715
technerd Avatar asked Jan 10 '16 07:01

technerd


People also ask

What is the difference between guard and if else in Swift?

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.

What is the purpose of if/else statement?

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?

What happens if the expression in the if statement is true?

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.

What is the difference between IFIF and if else in C?

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


1 Answers

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

like image 78
Muhammad Saifullah Avatar answered Jan 04 '23 19:01

Muhammad Saifullah