An old C programmer could use some help with Swift.
I don't understanding something about the if-case syntax. E.g.:
if case 20...30 = age {
print ("in range.")
}
The case 20...30 = age appears to be the conditional test for the if statement. So I was initially confused to see the assignment operator ('=') used instead of a comparison operator ('==').
Ok, I thought to myself, that probably means the case statement is actually a function call that returns a boolean value. The returned value will then satisfy the comparison test in the if statement.
As an experiment, I tried treating the the case statement like a regular conditional test and placed parentheses around it. Swift will happily accept if (x == 5) or if (true). But if (case 20...30 = age) generates an error. So the case statement doesn't seem to behave like function.
I'm just curious to understand what's happening here. Any insight would be greatly appreciated.
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
}
@matt does a good job of explaining what that code does. I'm here to suggest a better alternative.
Updated answer: I agree with the commenters, that using contains(_:) is the most clear:
if (20...30).contains(age) {
print("in range.")
}
Old answer
You can use the ~= operator to check ranges. It's a regular operator/function that just returns a Bool, with no special language magic.
if 20...30 ~= age {
print("in range.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With