How do you beautify guard-else conditions?

This looks horrible to me.

Screen Shot 2016-08-23 at 11.03.47 AM

This looks wrong too:

Screen Shot 2016-08-23 at 11.06.56 AM

And so does this:

Screen Shot 2016-08-23 at 11.07.50 AM

And this:

Screen Shot 2016-08-23 at 11.08.25 AM

And while we’re at it  these two too, both of which require hand-indenting while fighting Xcode:

Screen Shot 2016-08-23 at 11.17.53 AM

Screen Shot 2016-08-23 at 11.17.59 AM

This is among the least bad:

Screen Shot 2016-08-23 at 11.08.59 AM

What would you do to fix it?

Patrick Perini suggests:

Greg Titus thought using a simpler clause and a Never-returning function might be better. Here’s some code where I incorporated his feedback:


  • I do exactly like you, except with only one tab inside the braces.

  • I usually go for enclosing the condition between the `guard` and the `else`:

          nums.count == agruments.count
        else {
          print("Usage: \(appName) ")

    I find it seperates condition from code nicely while still maintaining a nice level of indentation.

    • Marcus’ formatting is the right one as I use it too 😉

    • Yes. This is nice.

    • That requires you to manually indent your code, though. :/

      • The big problem there is really Xcode. It’s woeful for text handling. Just try and paste any random block of text in, and see what it gives you; different results from line-to-line. It’s always been that way. Do not get me started on the ill-conceived “line everything up with colons” idiocy of some years back…

    • This is objectively the best possible solution… and a wet raspberry to XCode.

  • let isValidUsage = !argument.isEmpty &&
        nums.count == arguments.count
    guard isValidUsage else {
        print("Usage: \(appName) ")
    • this is my favorite pattern in general for any boolean that is not very obvious.

    • I just wanted to post the same variant using a temporary variable 🙂

  • At the risk of being hanged from the nearest tree by the curly brace correct masses, this is they way my code would look:

        nums.count == arguments.count
        print("Usage: .... ")

    Why must we be afraid to use white-space? The style that was used in the K&R C book all those years ago was intended to save paper.

    • Of course, posting destroyed my indentation! Imagine spaces before the statements between guard and else, and spaces before the statements bewtween the {}. guard, else, and {} are all at the same indent.

      • It’s (a slightly modified?) Allman indentation style.
        It isn’t popular, but it’s how I do it, too. (And I’m ok if almost everyone else is wrong. 🙂

        I think the advantages are:
        o it visually parses the code (so I don’t have to waste brain cycles);
        o it aligns things of equal importance (which keeps my OCD happy); and
        o it just gives the code space to breathe (I find it aesthetically pleasing / relaxing).

        • Allmän style is definitely the correct style. All this nonsense about putting the opening brace at the end of the line with the keyword is nonsense and it really annoys me that you have to fight Xcode to do it right. One of the few areas in which Eclipse is superior IMO is the power of the code formatting tools which allow you to choose almost any brace formatting style you like.

  • I think you’re trying too hard to make it resemble if-else style statements. It’s supposed to be a 1-liner. if it leaks on more than 1 line then so be it

    • Guard is a kind of if statement. While you are at it, why not put your if statements all on one line? My curly brace style is vindicated in the excellent book “Code Complete”.

      • Oooh, religion!

        Code Complete is an excellent book, but the hanging curly brace style on an if-else is worthy of spankings. Many, many spankings.

        The death penalty should be reserved for people who do this:

        if(something) // white-space hate crime!


        We’re not computers, Sebastian.

        I joke. The death penalty is reserved for people who have ever written code like this:

        if (something)

        (Hi Erica! 🙂

        Thankfully, Swift has made such things not only a Thought Crime, but has abolished the wicked practice.

      • Actually no. I once attended a course that was given by Steve McConnell and at the end, as a light hearted question, we asked him about how to do the braces. His opinion is that a space in hell is reserved for One True Brace Style (how can anybody pretend that “} else {” is anything but horrible) but Allman style was not far behind.

        • Well, you know what they say about opinions… I’ve been using my current style for over 20 years, modifying it to suit languages and IDEs and the practicalities of reading/writing code. Appeals to authority aren’t going to change that. I’m open to constructive ideas about programming, but not dogma or ideas-from-authority. People have different needs: I prefer to read AND write code that looks as much like English as possible. (And thus look at functional programming fashions like diseases of language.)

  • In ancient Persia, people were put to death for doing this:


    (The Persians were a wise people. Mind you, they would have executed the Xcode team many times over for their crimes against tabs and indentation.)

    I much prefer Patrick Perini’s approach:

        guard (
            nums.count == arguments.count
        ) else {
          print("Blah blah")
    • That’s just horrible. “) else {” is worse than “} else {“

  • I would write:

    guard !argument.isEmpty, nums.count == arguments.count else 
        print("Usage: \(appName) ")
    • With the statements in the curly-brackets indented, which they were when I submitted, but aren’t now!

  • Can’t we get a .isNotEmpty method so as not to require the “!”

    • Yeah, I really don’t like the use of negation at the start of a test like that. Especially since the advent of forced-unwrapping in Swift. It hurts my brain to read.

  • I’m not sure of the particular advantage of a guard in this case where there are no unwrapping of optionals. Why not just use an if statement?

  • Does anyone know the rationale for needing an “else” with guard in the first place? It feels forced — we would consider it very strange if a developer wanted to write

    “if else { }”

    Why not just “guard { }” ?

    • My code excerpts didn’t come out as intended. They were supposed to have conditions between the if and else, and between the guard and { }, and have “do stuff” code between the { }. YAMF = Yet Another Markup Failure.

  • Can’t we just get rid of else? Can we? It adds nothing, in fact it slows me down because I keep forgetting to add it, and if it’s always necessary then it might as well not be there

    I’m sure there’s a ‘frequently rejected proposals’ entry for this, but I’m digging in!

    • Good point on “else”.

      guard let wth = thereMustBeAReason() else {

      Swift3ElseWaitWhat.playground:: ‘++’ is unavailable: it has been removed in Swift 3

  • I agree with losing the else keyword. Also, it would be nice if there would be a way, if optionally/default desired. to somehow eliminate the “exit” statement in the else clause if with an some modification of the guard keyword which would provide an implicit exit. That way, Imo, the else clause (where the else keyword would also be gone) would be much easier to visually scan and type for many situations.

  • I think the behavior would be less completely obvious at a glance without the “else”, that tells your eyes right away that the attached clause is what executes if the conditions *aren’t* all true, so I can understand why it’s there; though I feel like that may only be necessary because “guard” itself fails to do that. Maybe they could have gone with, say, “unless” rather than “guard”, leaving out the “else” but otherwise being semantically identical.

  • This is probably heresy, but I like to seperate out my guard statements (note: Only a beginner swift programmer).

    func TestFunc(check: Bool, name: String?) -> Bool {
    guard check else { fatalError() }
    guard name != nil else { return false }

    return true

    • I use Adrian’s formation quite often, especially for short length statements. I also tend to do similar things with switch statements with the addition of tabbing the code executed to the same column. As an aside, the Pascal “case” statement is better than the switch statement Imo, since each case doesn’t need a keyword.