Swift-style-guide: 如果与守卫

创建于 2018-10-25  ·  3评论  ·  资料来源: raywenderlich/swift-style-guide

当前的样式指南很清楚使用guard而不是嵌套if ,但它可以显示一个示例,什么时候应该使用if而不是guard ,又名在不需要解包选项的情况下:

首选:

if !success { return false }

非首选:

guard success else { return false }

最佳描述: https ://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

最有用的评论

我几乎会说失败的守卫部分涵盖了这一点:
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
}

所有3条评论

我几乎会说失败的守卫部分涵盖了这一点:
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 - 是的,或者您只需要退出(无论是否由于失败)。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

fabienwarniez picture fabienwarniez  ·  9评论

aramezk picture aramezk  ·  9评论

rayfix picture rayfix  ·  3评论

icanzilb picture icanzilb  ·  6评论

sima-11 picture sima-11  ·  5评论