我几乎会说失败的守卫部分涵盖了这一点:
Guard statements are required to exit in some way.
...或者正如 Natasha 的博客所说:
think of guard as a lightweight Assert
因此,您应该这样做:
guard success else { return false }
guard
这里的好处是编译器会保证退出。 例子:
// This compiles fine and a bug risks going unnoticed
if !success {
// Some code here
// Forgot the return statement
}
// Compiler error, you are required to return and the bug is prevented
guard success else {
// Some code here
// Forgot the return statement
}
@RobertGummesson所以你的经验法则是——即使你不需要解开选项——如果遇到需要退出的失败,你会使用guard
而不是if
。 正确的?
@agirault - 是的,或者您只需要退出(无论是否由于失败)。
最有用的评论
我几乎会说失败的守卫部分涵盖了这一点:
Guard statements are required to exit in some way.
...或者正如 Natasha 的博客所说:
think of guard as a lightweight Assert
因此,您应该这样做:
guard
这里的好处是编译器会保证退出。 例子: