Hacker News new | ask | show | jobs
by NobodyNada 2 hours ago
guard is an inverted if statement, with the additional requirement that the branch must exit the parent scope. It's useful sometimes for readability, particularly for avoiding the "pyramid of doom" when you have a lot of preconditions that need to be checked:

    if fooOK 
        if barOK {
            if bazOK {
                // do something
            }
        }
    }
can be written as:

    guard fooOK else { return }
    guard barOK else { return }
    guard bazOK else { return }
    // do something
Obviously there are other options (like writing a negated if), but sometimes guard is more readable. It's a style thing.

The more important use case for guard is that 'guard let' statements can pattern-match and introduce bindings that are valid for the rest of the scope:

    guard let foo = someOptional else { return }
    print(foo);
This is useful enough that Rust copied it in the form of 'let ... else {}' statements (but did not bring over boolean guard statements).