【发布时间】:2021-02-05 14:09:19
【问题描述】:
我有一个按 y 位置排序的 SCNNode 数组(浮点数):
nodesSortedByY = scene.rootNode.childNodes.sorted { $0.position.y > $1.position.y }
我想做的是从 nodesSortedByY 获取一个新数组,其中 y 值在一定范围内,与 subscript 的工作方式类似,但传递的是实际值而不是索引。
例如:
let nodesSortedByY = [5.0, 4.0, 4.0, 3.0, 2.0, 2.0, 1.0]
let subRange = nodesSortedByY(4.0...2.0)
print(subRange) // [4.0, 4.0, 3.0, 2.0, 2.0]
我尝试使用最初与 this binary search 结合的索引,但如果数组中不存在这些值,则它不起作用:
let yPositions = nodesSortedByY.map({ $0.position.y })
let firstIndex = yPositions.binarySearch(forFirstIndexOf: firstValue) ?? 0
let lastIndex = yPositions.binarySearch(forLastIndexOf: lastValue) ?? 0
nodesSortedByY[lastIndex...firstIndex]
【问题讨论】:
-
您在寻找
filter()吗?let filtered = nodesSortedByY.filter({ (2.0...4.0).contains($0) }) -
不完全是,它必须以某种方式被一系列节点 y 位置过滤?
-
如果“y”的值在 2.0 和 4.0 之间,您不想获取它们吗?这就是过滤器的作用。否则,保留您的最后一个想法:
let lowerBound = nodesSortedByY.firstIndex(where: { $0 <= 4.0 }) let upperBound = nodesSortedByY.lastIndex(where: { $0 >= 2.0 }) let sub = nodesSortedByY[lowerBound!...upperBound!] -
我仍然想要一个 SCNNode 数组,但按
y对其进行排序并通过节点 y 值获取新的范围数组 -
我猜是这样,但作者使用了
map,并将他的示例简化为[Double],但我的解决方案应该可以工作。
标签: swift