我需要像这样实现体验过滤器
- 0 到 2 岁
- 2+ 到 4 岁
在swift范围内如何表达?
问题是我不能表达超过 2 到 4 年。虽然我可以做的少于上限。例如像这样
let underTen = 0.0..<10.0
我需要这样的东西(大于下限)
let uptoTwo = 0.0...2.0
let twoPlus = 2.0>..4.0 // compiler error
目前我在做
let twoPlus = 2.1...4.0
但这并不完美。
最佳答案
nextUp
来自 FloatingPoint
协议(protocol)
您可以使用 nextUp
Double
的属性,如 FloatingPoint
protocol 中的蓝图所示Double
符合
nextUp
The least representable value that compares greater than this value.
For any finite value
x
,x.nextUp
is greater thanx
. ...
即:
let uptoTwo = 0.0...2.0
let twoPlus = 2.0.nextUp...4.0
属性(property)ulp
,也在 FloatingPoint
协议(protocol)中绘制,已在您的问题的评论中提到。对于大多数数字,这是 self
和下一个更大的可表示数字之间的差异:
ulp
The unit in the last place of self.
This is the unit of the least significant digit in the significand of
self
. For most numbersx
, this is the difference betweenx
and the next greater (in magnitude) representable number. ...
nextUp
本质上是返回 self
的值加上 ulp
。因此,对于上面的示例,以下是等效的(而在此用例中,imo,nextup
应该是首选)。
let uptoTwo = 0.0...2.0
let twoPlus = (2.0+2.0.ulp)...4.0
您可能还想考虑将 twoPlus
中的下限文字替换为前面 uptoTwo
范围的 upperBound
属性:
let uptoTwo = 0.0...2.0 // [0, 2] closed-closed
let twoPlus = uptoTwo.upperBound.nextUp...4.0 // (2, 4] open-closed
if uptoTwo.overlaps(twoPlus) {
print("the two ranges overlap ...")
}
else {
print("ranges are non-overlapping, ok!")
}
// ranges are non-overlapping, ok!
关于快速范围大于下限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437839/