I originally posted this in swift-users, and it garnered some level of positive 
reaction, so I thought I would try it again here.

We all constantly write code that checks a value against arbitrary ranges - 
subsets of an array, characters within a string, etc. This is a common example:

if myVal >= oneLimit && myVar <= twoLimit { // something }

Swift introduced a very nice range system that is used to represent these sorts 
of spans-within-limits, which greatly clarifies common code like this...

for c in cards[0..<10] { // something }

My proposal is that this same "in" syntax be allowed in an if statement. Thus 
the limit check above would become:

if myVal in [oneLimit...twoLimit] { // something }

The code is somewhat more terse, which is a common goal in Swift. It also more 
clearly states what the purpose of the code - this is a range check, not some 
arbitrary mathematical comparisons. It also has the advantage that if myVal is 
expensive, a func for instance, it only gets evaluated once. Effectively it 
replaces:

let myVal = someExpensiveFunction()
if myVal >= oneLimit && myVar <= twoLimit...

with a single line of code.

I note that there are ways to accomplish this already in Swift 2, but I find 
them unsatisfying, and somewhat unnatural. They are definitely not 
"discoverable". which I believe the in statement would be. The current solution 
is the pattern-matching if, like this:

if case 0...100 = someInteger

or

if 0...100 ~= someInteger

I see two problems with this approach. Once is that the "if case" structure 
strikes me somewhat odd on it's own, but more specifically I think everyone 
finds the syntax "backward", we normally code the tested item on the left and 
limits on the right, and this reversal seems unnatural to me (in spite of it 
being identical in code terms). But I think the real issue is that both 
examples require special syntax that is very different than other languages or 
even most constructs in Swift itself, whereas in is already used in exactly the 
fashion I propose.

I don't believe that re-using "in" would greatly burden the language, while 
offering the same behaviour as the pattern-matching-if in a much more natural 
and already-used syntax.



_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to