Swift-style-guide: si vs guardia

Creado en 25 oct. 2018  ·  3Comentarios  ·  Fuente: raywenderlich/swift-style-guide

La guía de estilo actual es clara con respecto al uso guard en lugar de anidar if , pero podría mostrar un ejemplo cuando se debe usar if en lugar de guard , también conocido como donde no se necesita desenvolver los opcionales:

Privilegiado:

if !success { return false }

No preferido:

guard success else { return false }

Mejor descrito aquí: https://www.natashatherobot.com/swift-when-to-use-guard-vs-if/

Comentario más útil

Casi diría que la sección Falla de guardias cubre esto:
Guard statements are required to exit in some way.

... o como dice el blog de Natasha:
think of guard as a lightweight Assert

Por lo tanto, debe hacer:

guard success else { return false }

El beneficio de guard aquí es que el compilador garantizará la salida. Ejemplo:

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

Todos 3 comentarios

Casi diría que la sección Falla de guardias cubre esto:
Guard statements are required to exit in some way.

... o como dice el blog de Natasha:
think of guard as a lightweight Assert

Por lo tanto, debe hacer:

guard success else { return false }

El beneficio de guard aquí es que el compilador garantizará la salida. Ejemplo:

// 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 , por lo que su regla general sería que, incluso si no necesita desenvolver las opciones, usaría guard sobre if si encuentra una falla que requiere salir. ¿Correcto?

@agirault : sí, eso o simplemente necesita salir (ya sea que se deba o no a una falla).

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

rwenderlich picture rwenderlich  ·  29Comentarios

rayfix picture rayfix  ·  3Comentarios

Lweek picture Lweek  ·  5Comentarios

sima-11 picture sima-11  ·  5Comentarios

rayfix picture rayfix  ·  3Comentarios