Search code examples
iosswiftreturnguard

How to create an elegant guard / return statement in Swift that gives output?


For example, this works:

guard condition == true else { return }

Which is fine, but creates a silent failure. What would be nice is to have a static function that could output feedback whilst also returning. Something like:

guard condition == true else { stop("condition was false") }

Am I living in dreamland here, or might this be possible?

Of course, I recognise that the following is possible:

guard condition == true else { 
    print("condition was false")
    return
}

But is boilerplate heavy and kind of ugly. I have guard statements everywhere, this sort of code is: 1. useful; but 2. would bulk out my code by, like, 10% minimum.

It's utopian of me I know, but I would prefer an elegant solution. Anyone?


Solution

  • It really depends on what your function is all about. Typically methods with guard statements either have no return value or return optionals.

    func myReturn() -> String? {
        guard condition else { return nil }
    }
    

    if you want an analogue of stop, well, you could throw an Error, or even a fatalError

    func myReturn() throws -> String {
        guard condition else {
             throw BadConditionError
         }
    }
    

    Or

    func myReturn() -> String {
        guard condition else {
             fatalError("Bad condition")
         }
    }
    

    guard is an early exit mechanism, it prevents your program from getting into invalid state, use it accordingly. I'd also recommend reading on defer mechanism.