swift2 – Swift的guard关键字

前端之家收集整理的这篇文章主要介绍了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)")
原文链接:https://www.f2er.com/swift/321773.html

猜你在找的Swift相关文章