swift2 – Swift的guard关键字
发布时间:2020-12-14 06:18:48 所属栏目:百科 来源:网络整理
导读:Swift 2引入了guard关键字,可以用来确保各种数据配置准备就绪。我在 this website上看到的一个例子演示了一个submitTapped函数: func submitTapped() { guard username.text.characters.count 0 else { return } print("All good")} 我想知道如果使用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 }
同样的模式也适用于非可选值: 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解开任何可选项,
。 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)") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |