Swift's guard statement

Source: Internet
Author: User

Transferred from: HTTP://WWW.JIANSHU.COM/P/3A8E45AF7FDD

This article is translated from:
http://ericcerney.com/swift-guard-statement/
Hara Ecerney
Original article posted on 2015-06-10
* Translator NOTE: This syntax is swift2.0 new feature, currently (2015-07-30) only Xcode 7 beta support, XCODE6 does not support.

When I first saw Swift's guard statement at Apple's platform state of the Union, I didn't quite understand why I could use it later. This statement is described as follows:

As with the IF statement, Guard is also based on the Boolean value of an expression to determine whether a piece of code should be executed. Unlike the IF statement, the guard executes the code only when the condition is not satisfied. You can think of guard approximation as an assert, but you can gracefully exit rather than crash.

Even if I look at some examples, I just think it's a more confusing way to achieve what we've already been able to do with an optional binding (optional binding) or a separate If-else statement.
It wasn't until I started talking about this statement on Twitter conversation that I realized that this grammar really had some
A very interesting advantage.


Swift Guard Bodyguard Specifics

Let's compare the current wording and the new guard statement with a simple comparison:

func fooManualCheck(x: Int?) {    if x == nil || x <= 0 { // 不符合值的要求时,写点代码 return } // 使用x x!.description}

This is the most basic objective-c way to ensure that a variable really exists and conforms to a condition. There is no big problem, but there are some drawbacks:

    1. You are checking for a condition that does not meet your expectations, rather than checking the value you want. If you add a bunch of criteria like this, the code becomes poorly understood. You're here in fact waiting for your condition to pass.
    2. If the result of the preceding condition is not met, you will have to force your variable to be split.

Swift has made the problem easier with optional bindings and solved some of the drawbacks above:

func fooBinding(x: Int?) {    if let x = x where x > 0 { // 使用x x.description } // 如果值不符合条件判断,就执行下面的代码}

This function does not have 2 flaws in the first function, but introduces a new one. You put the code you want to write in all the conditional judgments, not later. You may not immediately be aware of the problem, but you can imagine how difficult it would be to understand if you had nested a lot of criteria before your code was executed.

The solution to this is to first check each condition, and exit if the condition is not met. This makes it easy to see what conditions will allow this function to exit.

I've heard that this is called Bodyguard mode (bouncer pattern), which is quite reasonable. You need to get them out before the bad things come in. This allows you to think about only one situation at a time, rather than figuring out how to put all the conditions together at the same time.

This is the Guard statement:

func fooGuard(x: Int?) {    guard let x = x where x > 0 else { // 变量不符合条件判断时,执行下面代码 return } // 使用x x.description}

Use the Guard statement to resolve the above 3 issues:

    1. Check the conditions you want, not what you expect. is similar to the Assert. If the condition does not conform, the else statement of the guard runs, which exits the function.
    2. If a condition is passed, the variable of the optional type is automatically disassembled in the range called by the Guard statement-in this case the range is inside the Fooguard function. This is a very important, but somewhat strange, feature, but it makes the guard statement very practical.
    3. Checking the situation you don't expect makes the functions you write easier to read and easier to maintain.

The use of variables of non-optional types also works:

func fooNonOptionalGood(x: Int) {    guard x > 0 else { // 变量不符合条件判断时,执行下面代码 return } // 使用x}func fooNonOptionalBad(x: Int) { if x <= 0 { // 变量不符合条件判断时,执行下面代码 return } // 使用x}
Summarize

Hopefully this simple example tells you that you can use guard in your swift code right away, making your function/method clearer. It's easy for us to judge a new feature, just try it and see if it works for you.

The shift from objective-c to Swift is huge, not just syntax, but how you look at your code architecture. Only if you take the initiative to change your intentions, expand your own patterns and ways every day, you will benefit from this wonderful new language.

Just tell me what other fun things have been found, and this grammar is new to me.



Wen/ray16897188 (author of Jane's book)
Original link: HTTP://WWW.JIANSHU.COM/P/3A8E45AF7FDD
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Swift's 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.