original source : https://stackoverflow.com/questions/37888376/how-case-works-in-if-case
The operator is if case
, so you can’t put parentheses. The syntax and behavior are based on those of the case
statement in a Swift switch
statement (see my online book if you need details). In a case
statement, 20...30
is an interval, used as a pattern, which operates by using contains
against the interval. The equals sign is indeed truly confusing, but that was their first attempt at a syntax for expressing what the case
statement should be comparing with (i.e. the tag that comes after the switch
keyword in a switch
statement).
So, if you understand this:
switch age {
case 20...30:
// do stuff
default:break
}
… then you understand how it is morphed directly into this:
if case 20...30 = age {
// do stuff
}