Swift-style-guide: wenn gegen Wache

Erstellt am 25. Okt. 2018  ·  3Kommentare  ·  Quelle: raywenderlich/swift-style-guide

Der aktuelle Styleguide ist klar in Bezug auf die Verwendung guard anstelle der Verschachtelung von if , aber er könnte ein Beispiel zeigen, wenn if anstelle von guard , alias, verwendet werden sollte wobei kein Auspacken von optionalen Komponenten erforderlich ist:

Bevorzugt:

if !success { return false }

Nicht bevorzugt:

guard success else { return false }

Am besten hier beschrieben: https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

Hilfreichster Kommentar

Ich würde fast sagen, dass der Abschnitt Failing Guards dies abdeckt:
Guard statements are required to exit in some way.

...oder wie es in Nataschas Blog heißt:
think of guard as a lightweight Assert

Sie sollten daher Folgendes tun:

guard success else { return false }

Der Vorteil von guard ist hier, dass der Compiler den Ausstieg garantiert. Beispiel:

// 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
}

Alle 3 Kommentare

Ich würde fast sagen, dass der Abschnitt Failing Guards dies abdeckt:
Guard statements are required to exit in some way.

...oder wie es in Nataschas Blog heißt:
think of guard as a lightweight Assert

Sie sollten daher Folgendes tun:

guard success else { return false }

Der Vorteil von guard ist hier, dass der Compiler den Ausstieg garantiert. Beispiel:

// 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 , Ihre Faustregel wäre also, dass Sie - selbst wenn Sie keine Optionen auspacken müssen - guard über if verwenden würden, wenn Sie auf einen Fehler stoßen, der das Beenden erfordert. Richtig?

@agirault - Ja, entweder das oder Sie müssen einfach beenden (unabhängig davon, ob es sich um einen Fehler handelt oder nicht).

War diese Seite hilfreich?
0 / 5 - 0 Bewertungen

Verwandte Themen

samkim102 picture samkim102  ·  4Kommentare

jackwu95 picture jackwu95  ·  6Kommentare

hollance picture hollance  ·  28Kommentare

aramezk picture aramezk  ·  9Kommentare

ghost picture ghost  ·  26Kommentare