快速范围大于下限

标签 swift swift3 nsrange

我需要像这样实现体验过滤器

  • 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 than x. ...

即:

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 numbers x, this is the difference between x 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/

相关文章:

iOS - 注销后重置 UITabBarController/UIViewController 状态

ios - 奇数或偶数的 NSRange 数组

swift - WordPress Swift 构建器框架轮播箭头拆分

ios - Swift 中的异步 NSOperation 依赖

swift - 如何解决Xcode 8.3 beta中的 "String interpolation produces a debug description for an optional value; did you mean to make this explicit?"?

ios - 如何使用 NSRange 创建 NSArray 的子数组?

objective-c - nsrange.location 不完全是麻烦 makerange 子串 ios objective c

swift - 如何打开选项,我怎样才能编写这段代码以使其没有任何选项?或者 !在其中,或者有可能吗?

ios - 如何将 UIActivityIndi​​catorView 添加到 WKWebView?

iOS View 可见性消失