Gmail_2
(Gmail 2)
1
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
You can do this:
let testValue = 0.3
// Using instance method.
if (0.0..<1.0).contains(testValue) {
print("Hello, world.")
}
// Using pattern matching operator.
if 0.0..<1.0 ~= testValue {
print("Hello, world.")
}
Preston
···
On Feb 2, 2016, at 4:53 AM, Gmail 2 via swift-evolution <swift-evolution@swift.org> wrote:
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
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution