kenryuakuma
kenryuakuma

Reputation: 97

Guard Case Assignment

Well...here is the code

func howMany() -> Int {
   return 10
}

func Call() -> Void {
   guard case let output = howMany(), output > 5 else { return }
}

Call()

I do not really understand how the guard case works. This looks pretty much like a pattern matching condition where we compare whether the result of howMany() is equal to output, if it is, assign the value to output and then compare it to the literal value 5. However, when I deleted the line of output > 5, the compiler said, "the guard condition is always true, body is unreachable."

According to the pattern, if we translate it into a switch statement, it looks pretty much like this

switch howMany() {
   case let output where output > 5:
      break;
}

The question is if it could be directly translated into the switch statement, then there should not be a warning of "the guard condition is always true, body is unreachable" when we delete the where condition.

I hope somebody could shed some light on this.

Upvotes: 4

Views: 944

Answers (1)

Rob
Rob

Reputation: 437452

Consider:

func foo() {
    guard case let output = howMany(), output > 5 else {
        print("less than or equal to 5")
        return
    }

    print("\(output) is greater than 5")
}

That is roughly equivalent to:

func bar() {
    switch howMany() {
    case let output where output > 5:
        print("\(output) is greater than 5")

    default:
        print("less than or equal to 5")
        return
    }
}

If you remove that > 5 criteria:

func foo() {
    guard case let output = howMany() else {
        print("less than or equal to 5")
        return
    }

    print("\(output) is greater than 5")
}

You get your warning:

'guard' condition is always true, body is unreachable

That warning is correct, because the body is unreachable.

And if you do the equivalent in the switch example:

func bar() {
    switch howMany() {
    case let output:
        print("\(output) is greater than 5")

    default:
        print("less than or equal to 5")
        return
    }
}

If you do that, you will receive an analogous warning:

default will never be executed

And, again, it makes sense, because default will not be reached.

Now, consider your example switch with no default clause:

func bar() {
    switch howMany() {
    case let output:
        print("output:", output)
    }
}

You don't receive a warning here only because there is no default clause (the analog of the "body" of the guard statement).

Upvotes: 5

Related Questions