swift2 – Swift的guard关键字

Swift 2引入了guard关键字,可以用来确保各种数据配置准备就绪。我在 this website上看到的一个例子演示了一个submitTapped函数:
func submitTapped() {
    guard username.text.characters.count > 0 else {
        return
    }

    print("All good")
}

我想知道如果使用guard是任何不同于做它的老式方式,使用if条件。它是否带来好处,你不能通过使用简单的检查?

阅读 this article我注意到使用卫报的巨大好处

这里可以比较guard的用法和例子:

这是没有警卫的部分:

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

    // Value requirements not met,do something
}

>这里你把你想要的代码在所有的条件

你可能不会立即看到一个问题,但你可以想象如果它嵌套了许多条件,所有需要在运行你的语句

清理它的方法是先进行每一个检查,如果没有满足则退出。这使得容易理解什么条件将使此功能退出。

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

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. 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

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

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
}

如果你还有任何问题,你可以阅读整篇文章:Swift guard statement.

包起来

最后,阅读和测试我发现,如果你使用guard解开任何可选项,

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块内部使用

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...