Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with swift enum syntax [duplicate]

Tags:

swift

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.

like image 685
oldCoder Avatar asked Mar 09 '26 13:03

oldCoder


2 Answers

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
}
like image 144
matt Avatar answered Mar 11 '26 01:03

matt


@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.")
}
like image 27
Alexander Avatar answered Mar 11 '26 02:03

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!