斯威夫特的后卫关键字 [英] Swift's guard keyword

查看:96
本文介绍了斯威夫特的后卫关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 2引入了guard关键字,该关键字可用于确保已准备好配置各种数据.我在此网站上看到的一个示例演示了一个commitTapped函数:

Swift 2 introduced the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function:

func submitTapped() {
    guard username.text.characters.count > 0 else {
        return
    }

    print("All good")
}

我想知道使用guard是否与使用if条件的老式方法有所不同.它会带来好处吗?使用简单的支票无法获得这些好处?

I am wondering if using guard is any different than doing it the old fashioned way, using an if condition. Does it give benefits, which you could not get by using a simple check?

推荐答案

阅读本文我注意到使用守卫

您可以在此处将卫兵的使用与示例进行比较:

Here you can compare the use of guard with an example:

这是没有保护的部分:

func fooBinding(x: Int?) {
    if let x = x where x > 0 {
        // Do stuff with x
        x.description
    }

    // Value requirements not met, do something
}

  1. 在这里,您要在所有情况下输入所需的代码

  1. Here you’re putting your desired code within all the conditions

您可能不会立即看到与此相关的问题,但是您可以想象,如果将它嵌套在运行语句之前需要满足的所有条件的情况下,它将变得多么混乱

You might not immediately see 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

清除此问题的方法是先进行每项检查,如果未通过检查则退出.这样可以轻松了解导致此功能退出的条件.

The way to clean this up is to do each of your checks first, and exit if any aren’t met. This allows easy understanding of what conditions will make this function exit.

但是现在我们可以使用警卫了,我们可以看到可以解决一些问题:

But now we can use guard and we can see that is possible to resolve some issues:

func fooGuard(x: Int?) {
    guard let x = x where x > 0 else {
        // Value requirements not met, do something
        return
    }

    // Do stuff with x
    x.description
}

  1. 检查您想要的条件,而不是您不想要的条件.这又类似于断言.如果不符合条件, Guard的else语句将运行,这会中断该功能.
  2. 如果条件通过,此处的可选变量将在防护范围内自动为您解包 语句被调用–在这种情况下,使用fooGuard(_ :)函数.
  3. 您正在及早检查不良情况,从而使您的功能更具可读性且更易于维护
  1. 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 was called – in this case, the fooGuard(_:) function.
  3. You are checking for bad cases early, making your function more readable and easier to maintain

对于非可选值,同样的模式也适用:

This same pattern holds true for non-optional values as well:

func fooNonOptionalGood(x: Int) {
    guard x > 0 else {
        // Value requirements not met, do something
        return
    }

    // Do stuff with x
}

func fooNonOptionalBad(x: Int) {
    if x <= 0 {
        // Value requirements not met, do something
        return
    }

    // Do stuff with x
}

如果您还有任何疑问,可以阅读整篇文章:快速卫士声明.

If you still have any questions you can read the entire article: Swift guard statement.

总结

最后,通过阅读和测试,我发现,如果您使用防护来解开任何可选项,则

And finally, reading and testing I found that if you use guard to unwrap any optionals,

这些未包装的值会留在您的其余部分中供您使用 代码块

those unwrapped values stay around for you to use in the rest of your code block

.

guard let unwrappedName = userName else {
    return
}

print("Your username is \(unwrappedName)")

这里展开的值仅在if块内可用

Here the unwrapped value would be available only inside the if block

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)")

这篇关于斯威夫特的后卫关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆