noobsmcgoobs
noobsmcgoobs

Reputation: 2746

Guard statement in Swift has error if using return

I have this code

 guard let url = NSURL(string: urlString) else{

            print("No URL")
            return

        }

the return statement produces an error

Non-void function should return a value

Omitting the return gives me error below

'guard' body may not fall through, consider using 'return' or 'break' to exit the scope

How do I avoid this error?

Upvotes: 0

Views: 2767

Answers (1)

Craig
Craig

Reputation: 9330

The error is saying that your guard statement is within a func() that has an expected return value of some type

For example in the greet() function a String is returned… so the guard statement must return a String value. The type of the value you have to return from your guard statement will depend on the function that contains it.

func greet(person: String, day: String) -> String {
    guard person != "Homer" else {
        return "Sorry, no Homer's allowed"
    }

    return "Hello \(person), have a great \(day)"
}

greet(person: "Homer", day: "Monday")

greet(person: "Douglas", day: "Thursday")

If the String "Sorry, no Homer's allowed" isn't returned in the example greet() function you will see the same problem:

broken guard statement

A guard statement simply protects against an unusable state for the function it's enclosed in. So the return statement of a guard is just a form of early return for the function, as such, it must return the same type as the functions definition.

In the greet() function above the definition specifies that a String is returned (-> String) , so the return inside the guard's else block must also return a String.

Upvotes: 4

Related Questions