Joseph Beuys' Mum
Joseph Beuys' Mum

Reputation: 2284

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?

Upvotes: 1

Views: 2281

Answers (4)

ielyamani
ielyamani

Reputation: 18591

Use precondition instead of guard:

func test() {
    precondition(yourCondition, "This is an error message")
    //rest of your function
}

If yourCondition is false, the scope is going to be exited and the error message will be printed.

Upvotes: 5

Hardik Darji
Hardik Darji

Reputation: 3684

As I understand, you want to produce some output or show message on false condition or on nil value, before return in guard. Below is my thinking:

func checkForNil(value: Any?) -> Any?
    {
        if value == nil
        {
            //showMessage("Nil value...")
            print("nil value")
        }
        return value
    }

you can use this as below:

guard let obj = self.checkForNil(value: objLoggedInUser) else { return}

Upvotes: 1

inokey
inokey

Reputation: 6190

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.

Upvotes: 3

PGDev
PGDev

Reputation: 24341

Try using closures to get it working, i.e.

func func1(handler: ((String)->())) {
    let condition = (2 == 2)
    guard condition == true else {
        handler("condition was false")
        return
    }
}

func1 { (reason) in
    print(reason)
}

Upvotes: 0

Related Questions