4

Please, can anyone explain why this works?

func howMany() -> Int {return 11}
guard case let output = howMany(), output > 10 else {return}

I understand how guard/if/while/for case let works with enums. Pattern matching is great. But here is no enum and this works too. What is the language construct that allows that?

(This example was taken from Matt Neuburg's book.)

Michael Bernat
  • 486
  • 5
  • 16
  • 3
    In your case, `output` in an [identifier pattern](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html), which always succeeds. `switch` doesn't require a value to be an enum. – 4castle Nov 22 '17 at 21:41
  • Silly example, there's absolutely no reason to write this over `guard howMany() < 10 else { return }` – Alexander Nov 23 '17 at 00:05
  • There is at least one reason (except educational purposes): **output** variable remains in scope after guard and can be used. – Michael Bernat Nov 23 '17 at 10:31

1 Answers1

3

It's the if case construct. (guard is merely a negative if, if you see what I mean.)

The whole idea of this construct is that it lets you use an ordinary if or guard while taking advantage of switch case pattern matching. A major use is to do extraction of an associated value from an enum without the heavyweight switch construct, but you can use it anywhere that pattern matching in a condition makes sense (as here).

See also https://stackoverflow.com/a/37888514/341994

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Look for "if case" in the Index (or see p. 261 if you have the latest edition). – matt Nov 22 '17 at 21:35
  • Thanks, Matt! :) Now much clearer, as this works too: `switch howMany() { case let output: print("howMany:\(output)") }` – Michael Bernat Nov 22 '17 at 21:47
  • Exactly. The thing after the `=` in the `if case` would be the "tag" in the `switch` statement. – matt Nov 22 '17 at 21:48