Swift-style-guide: 対ガードの場合

作成日 2018年10月25日  ·  3コメント  ·  ソース: raywenderlich/swift-style-guide

現在のスタイルガイドは、 ifをネストする代わりにguardを使用することに関して明確ですが、 guard ifを使用する必要がある場合の例を示すことができます。必要なオプションのアンラッピングがない場合:

優先:

if !success { return false }

推奨されません:

guard success else { return false }

ここで最もよく説明されているのは、 https ://www.natashatherobot.com/swift-when-to-use-guard-vs-if/です。

最も参考になるコメント

私はほとんど、 FailingGuardsセクションがこれをカバーしていると言うでしょう:
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件

私はほとんど、 FailingGuardsセクションがこれをカバーしていると言うでしょう:
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なので、経験則では、オプションのラップを解除する必要がない場合でも、終了が必要な障害が発生した場合は、 ifよりも$ guardを使用します。 正しい?

@ agirault-はい、それか、単に終了する必要があります(失敗によるものかどうかは関係ありません)。

このページは役に立ちましたか?
0 / 5 - 0 評価

関連する問題

rwenderlich picture rwenderlich  ·  29コメント

luki picture luki  ·  3コメント

sima-11 picture sima-11  ·  5コメント

xezun picture xezun  ·  6コメント

gokselkoksal picture gokselkoksal  ·  9コメント