Reading 本文我注意到使用有很大的好处Guard
这里可以通过一个例子来比较guard的使用:
这是没有防护的部分:
func fooBinding(x: Int?) {
if let x = x where x > 0 {
// Do stuff with x
x.description
}
// Value requirements not met, do something
}
-
在这里,您可以在所有条件下输入所需的代码
您可能不会立即发现其中的问题,但您可以想象,如果它嵌套了许多在运行语句之前需要满足的条件,那么它会变得多么混乱
清理这个问题的方法是首先进行每项检查,如果不满足则退出。这样可以轻松了解什么条件会导致该函数退出。
但现在我们可以使用guard,我们可以看到这可以解决一些问题:
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
}
- 检查您确实想要的条件,而不是您不想要的条件。这又类似于断言。如果不满足条件,
Guard 的 else 语句被运行,它跳出了函数。
- 如果条件通过,这里的可选变量会在防护范围内自动为您解包
语句被调用——在本例中为 fooGuard(_:) 函数。
- 您尽早检查不良情况,使您的函数更具可读性且更易于维护
同样的模式也适用于非可选值:
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
}
如果您还有任何疑问,可以阅读整篇文章:迅速守卫声明。
包起来
最后,阅读和测试我发现如果你使用防护来解开任何选项,
这些未包装的值会留在您的其余部分中供您使用
代码块
.
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)")