When (not) to use guard


guard is one of my favorite features of Swift 2. It’s one of those subtle syntactical constructs we could totally do without. And yet having it is such a delightful win. It makes our methods cleaner and easier to read, it helps express the “early exit” intention, and adds a little extra safety.

However, it’s important to learn and understand how to use guard properly. It has its place, but it’s not meant to replace if..else and if let in all cases. No matter how great guard is, it can easily be misapplied and forced into places where other constructs do a better job.

Here are some basic guidelines for when to guard, and when not to:

I'm definitely guilty of underusing guard in my Swift code. But this article has a lot of really good explanations and examples, so now I'm itchin' to do some refactorin'.