Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you put a guard statement inside a function in Swift?

I don't understand why you can't have a guard statement inside of a returning function.

func sayHello(text: String?) -> String {
    guard let whatever = text else {
        ...
        return
    }
    return "aString"
}

Why is the above incorrect? Xcode gives me the error "non-void function should return a value" on the return statement in the guard closure, like it thinks that return statement is the function's return statement. How do you differentiate between a guard's return statement and the function's return statement?

The same thing happens in completion handlers that do not return:

func anotherFunction() -> Bool {
    aFunction("hello", completion: { (status) -> Void in
        if status == "good" {
            return true // I want anotherFunction() to return this not the handler
        } else {
            return false
        }
    })
}

Xcode thinks that I am trying to have a void completion handler return a Bool, instead I want the function to return a Bool based on the result of the completion handler.

I think I understand why you can't do this in the completion handler example, but you should definitely be able to have a guard statement inside a non-void function. I tried replacing return (in the guard example) with break and continue, neither of which worked.

Thanks!

like image 301
Jake Avatar asked Jan 17 '26 22:01

Jake


1 Answers

The whole point here is...you can't return inside the execution of a completion handler. In your second case, if you want to return a boolean about the result of your completion handler, you'll have to make a local variable, set it in the result of your handler, and then return that outside of the handler. As for the first problem you're facing, Xcode is complaining because you've declared the function as returning a string, yet in your else statement you're trying to return void, which violates the return type of the function. You can do what you're trying to do, but you have to return at least an empty string.

like image 165
pbush25 Avatar answered Jan 20 '26 14:01

pbush25