我的代码:
let range = 30...200 //ranges may have different bounds
let index = range.firstIndex(of: 55)
问题是index
类型为ClosedRange<Int>.Index
目前尚不清楚如何将其转换为 Int
现在供进一步使用。
我知道将范围转换为数组并在其中查找 int 索引更简单,但它们以某种方式应该允许使用 ClosedRange<Int>.Index
本身
注意:可能有类似的问题,但都是关于如何转换 ClosedRange<Int>
到数组,而不是索引转换
最佳答案
ClosedRange<Bound>.Index
实际上只是一个枚举,不会告诉您任何有用的信息。
enum Index {
case inRange(Bound)
case pastEnd
}
像这样简单的事情就足以正确实现 Collection
的索引相关方法。和其他协议(protocol)要求。
firstIndex(of: 55)
将返回inRange(55)
如果 55 在范围内,且 pastEnd
否则。
另请注意 firstIndex
( and other Collection
methods ) 仅在 Bound
时可用。符合Stridable
和 Stride
符合SignedInteger
。毕竟,对待 ClosedRange<Double>
是没有意义的。或ClosedRange<String>
作为Collection
.
因此,像 firstIndex(of: 55)
这样的操作的唯一范围有道理,就是当 Bound: Stridable, Bound.Stride: SignedInteger
。您可以使用 distance(to: lowerBound)
找出该范围内元素的“数字”索引。 ,这是 Stridable
上的一个方法.
extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {
func numericIndex(of element: Bound) -> Bound.Stride? {
if contains(element) {
return element.distance(to: lowerBound)
} else {
return nil
}
}
}
对于ClosedRange<Int>
,这基本上是减法。 30...200 中的 55 指数就是 55 - 30 = 25。
关于swift - ClosedRange<Int>.Swift 中 Int 的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76753159/