Swift Guard Statement

Source: Internet
Author: User

When the first saw the Swift guard statement during Apple's Platform state of the Union, I couldn ' t quite understand why I would ever use it. Why is it it?

Like if the statement, guard executes statements based on a Boolean value of an expression. Unlike an if statement, guard statements only run if the conditions is not met. You can think for more like guard Assert A, but rather than crashing, you can gracefully exit.

Even after seeing some examples, I-only saw it as a confusing-to-accomplish what we already could with Optional Bindin G or with if-else statements alone.

Diving in

Let's take a simple example comparing current techniques vs using the new guard statement:

 1  func foomanualcheck (x:int?) { 2  if  x = = Nil | | X <= 0   { 3   Value requirements not met, do something  4  return  5   6  //  do stuff with x  8  x! .description  9 } 

This is the most basic objective-c style, sure a value exists and that it meets a condition. Now the works fine, but have a couple flaws:

    1. You ' re checking for a condition so you don't want, rather than checking for the value of you do want. Code becomes confusing if you had a bunch of checks like this. What's your ' re hoping for here's that your condition actually doesn ' t pass.
    2. You also need to force unwrap the optional value after the condition fails.

Swift gave us a-on-a-do-a-some of these flaws through Optional Binding:

 1  func foobinding (x:int?) { 2  if  Let x = x where  x > 0   { 3  //  do stuff with x  4   x.description  5  }  6  7  //  Value requirements not met, do something  8 } 

This removes both of the flaws, and the first function had, but adds a new one. Here you ' re putting your desired code within all the conditions, rather than afterward. You might isn't immediately see a problem with this, but are you could imagine what confusing it could become if it was nested WI Th numerous conditions that all needed to be met before running your statements.

The "the" and "the" to "your" to "do" checks first, and exit if any aren ' t met. This allows easy understanding of what conditions would make this function exit.

I ' ve heard this called the Bouncer Pattern, which makes a iot of sense. You want to get rid of the bad cases before they get in the door. It also allows you to think on one case at a time, rather than figuring out how all combinations need to work together.

Here enters the guard statement:

 1  func fooguard (x:int?)  { 2  guard Let x = x where  x > 0  else   { 3   Value requirements not met, do something  4  return  5   6  //  do stuff with x  8   x.description  Span style= "color: #008080;" >9 } 

Using guard solves all 3 of the issues mentioned above:

    1. Checking for the condition you does want, not the one of you don ' t. This again was similar to an assert . If the condition is not met, guard ' s else statement are run, which breaks out of the function.
    2. If the condition passes, the optional variable here's automatically unwrapped for your within the scope that the guard STA Tement was called–in the fooGuard(_:) function. This is a important, yet notably strange feature that really makes the guard statement useful.
    3. You is checking for bad cases early, making your function more readable and easier to maintain.

The cool thing is so this same pattern holds true for non-optional values as well:

1 func Foononoptionalgood (x:int) {2Guard x >0 Else {3         //Value requirements not met, do something4         return5     }6     7     //Do stuff with x8 }9  Ten func Foononoptionalbad (x:int) { One     ifX <=0 { A         //Value requirements not met, do something -         return -     } the      -     //Do stuff with x -}
Wrapping up

This simple example shows how do you could start using guard immediately in your Swift code to make your function/methods mor E clear. It's easy for us to immediately judge the value of a new feature until you give it a chance and see what it can O R can ' t do for you.

Going from objective-c to Swift are a huge change, not only to syntax, but how do you have the look at Architecting your code. You can have benefit from the awesome new language if you actively the change your mindset while writing code by expanding yo ur everyday patterns and style.

Reference: Swift Guard Statement

Reference: Swift's guard statement

Swift Guard Statement

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.