[swift-evolution] proposal to add "in range" operator
Gmail 2
leoyoontsaw at gmail.com
Tue Feb 2 05:53:54 CST 2016
Hello everyone,
I have a proposal to add an "in range” operator in swift.
##Current situation
Checking whether a value is or not within a certain range now depends on the control flow you use. for switch-statement, it is intuitive; but it is not for if-statement.
Example:
let testValue = 0.3
switch testValue {
case 0.0..<1.0: do something...
default: break
}
to write the same logic in if-statement, you have to write like this:
if testValue >= 0.0 && testValue < 1.0 {
do something...
}
The disadvantage here:
1. It’s wordy;
2. It’s risky to write the same variable name twice, typo can occur and be ignored;
3. It’s inconsistent with switch-statement.
##Proposed solution
Introduce a new operator to check a variable against a range.
Here is a drafted operator: ~ (infix operator)
With ~, the above if-statement can be rewritten like:
if testValue ~ 0.0..<1.0 {
do something...
}
looks much better.
What’s more, if combined with the draft proposal Generalized range operators in `for-in`loops and other purposes <https://github.com/apple/swift-evolution/pull/129>, this new operator would more powerful.
Thanks for reading
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160202/9f875423/attachment.html>
More information about the swift-evolution
mailing list