Tuesday 25 October 2016

Guard Statement In Swift3

Swift 2 introduces the guard statement. It was designed specifically for exiting a method or function early. The guard statement is ideal for getting rid of deeply nested conditionals whose sole purpose is validating a set of requirements. Take a look at the updated example in which I’ve replaced every if statement with the new guard statement.

Note*

guard statement always has an else clause. The else clause is executed if the condition of the guard statement evaluates to false. Using guard makes much more sense when you’re validating requirements.

Syntax:







Example: 










Output : It will print "fail" because we are passing nil in the function argument.

Now we are passing 56 in the function argument.












 Optional Binding   Vs  guard

Lets take same example with optional binding















Optional binding gives the same output as we have seen in above example with guard statement.

Problem with Optional Binding

There is a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements.

Why guard is better ?

1) Here we are checking for the condition you do want, not the one you don’t. This again is similar to an assert. If the condition is not met, guard‘s else statement is run, which breaks out of the function.

2) If the condition passes, the optional variable here is automatically unwrapped for you within the scope that the guard statement. This is an important feature that really makes the guard statement useful.

3) With the help of guard statement we can check for bad cases early, making your function more readable and easier to maintain.


No comments:

Post a Comment