轻松检查数字是否在 Dart 中的给定范围内?

ale*_*pfx 21 dart

Dart 中是否有运算符或函数可以轻松验证数字是否在范围内?类似于 Kotlinin运算符:

https://kotlinlang.org/docs/reference/ranges.html

if (i in 1..10) { // equivalent of 1 <= i && i <= 10
    println(i)
}
Run Code Online (Sandbox Code Playgroud)

小智 27

由于包含扩展函数,如果您可以进行非内联检查,则可以稍微更改此答案。

据我所知,没有内置函数可以实现这一点,但您可以轻松创建自己的扩展来num模拟这一点。

像这样的东西会模拟范围验证:

void main() {
  final i = 2;
  if (i.isBetween(1, 10)) {
    print('Between');
  } else {
    print('Not between');
  }
}

extension Range on num {
  bool isBetween(num from, num to) {
    return from < this && this < to;
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法尤其是 from 和 to 都是互斥的,但通过细微的调整和更好的命名,您可以轻松地为所有 Kotlin 范围检查创建扩展函数。


Ran*_*rtz 20

很简单,没有。只需使用1 <= i && i <= 10.


小智 5

I find using clamp more readable. So, to check if i is between 1 and 10, clamp it to the range and compare to itself.

if (i.clamp(1,10) == i) {
    print(i);
}
Run Code Online (Sandbox Code Playgroud)

Documentation for clamp

  • 似乎在计算方面需要做更多的工作,因为您实际上只需要该逻辑的比较内容,而不是该逻辑的新值部分。如果您想要符号方便,您可以将 . Between(low, high) 写为 num 的扩展。编辑:我看到另一个答案已经表明了这一点! (2认同)