Article Image
Article Image
read

Why Swift guard Should Be Avoided:

There’s been plenty written about guard since it was added to Swift, but in this article, Alexei Kzznetsov argues that if your functions are small enough, it shouldn’t be needed at all. He takes some example code from the Apple Swift book and refactors it, removing the need for the guard statements along the way.

Guard has one specific use case:

To ensure pre-existing conditions before proceeding into the execution of a function. If the conditions are not met you can clean up the application state, or show an error and simply return to the caller.

  • It’s concise
  • Its scope is plain and obvious
  • It’s clear. (You can have multiple ‘guard’ for different pre-conditions.)

Use guard for its use case only. But use it, no matter how small your function is. Leaving your application in an undefined state or consistency (you use guard in some part of the code, but something different in another) is worse than adding the few lines of code needed for guard. Your code should be readable by humans as well. It going to make it easier to debug it in the future. Note: Remember that you can use ‘defer’ to run code right before exiting the scope, no matter the state.

Blog Logo

Valentino Urbano


Published

Image

Valentino Urbano

iOS Developer, Swift, Writer, Husband

Back to Overview