我需要实现这样的体验过滤器
- 0到2年
- 2年以上至4年
如何在快速范围内表达?
问题是我不能表达超过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
但这并不完美。
FloatingPoint
协议中的nextUp
您可以使用Double
的nextUp
属性,如Double
符合的FloatingPoint
协议中的蓝图
nextUp
比较起来大于此值的最不可表示的值。
对于任何有限值
x
,x.nextUp
都大于x
。。。
即:
let uptoTwo = 0.0...2.0
let twoPlus = 2.0.nextUp...4.0
属性ulp
也是FloatingPoint
协议中的蓝图,已在对您的问题的评论中提到。对于大多数数字,这是self
和下一个更大的可表示数字之间的差异
ulp
处于自我最后位置的单位。
这是的有效位中最低有效位数的单位
self
。对于大多数数字x
,这是x
和下一个更大的(数量级)可表示的数字。。。
nextUp
本质上是在添加ulp
的情况下返回self
的值。因此,对于上面的示例,以下内容是等效的(而在本用例中,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!
您可以创建一个方法来识别下限以上的值,而不是创建一种新的范围类型:
extension ClosedRange {
func containsAboveLowerBound(value:Bound) -> Bool {
if value > self.lowerBound {
return self.contains(value)
}
else {
return false
}
}
}
像这样实现:
let r = 2.0...3.0
r.containsAboveLowerBound(value: 2.0) // false
r.containsAboveLowerBound(value: 2.01) // true
如果您的实际目的是使用范围进行筛选,那么将它们作为闭包如何?
let underTen = {0.0 <= $0 && $0 < 10.0}
let upToTwo = {0.0 <= $0 && $0 <= 2.0}
let twoPlus = {2.0 < $0 && $0 <= 4.0}
你可以像这样使用过滤闭包:
class Client: CustomStringConvertible {
var experience: Double
init(experience: Double) {self.experience = experience}
var description: String {return "Client((experience))"}
}
let clients = [Client(experience: 1.0),Client(experience: 2.0),Client(experience: 3.0)]
let filteredUnderTen = clients.filter {underTen($0.experience)}
print(filteredUnderTen) //->[Client(1.0), Client(2.0), Client(3.0)]
let filteredUpToTwo = clients.filter {upToTwo($0.experience)}
print(filteredUpToTwo) //->[Client(1.0), Client(2.0)]
let filteredTwoPlus = clients.filter {twoPlus($0.experience)}
print(filteredTwoPlus) //->[Client(3.0)]
我认为这样就可以了,
extension ClosedRange where Bound == Int {
func containsExclusiveOfBounds(_ bound: Bound) -> Bool {
return !(bound == lowerBound || bound == upperBound)
}
}