Reputation: 646
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.)
Upvotes: 4
Views: 1263
Reputation: 534977
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
Upvotes: 3