swift - ClosedRange<Int>.Swift 中 Int 的索引?

标签 swift indexing range variable-types

我的代码:

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 时可用。符合StridableStride符合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/

相关文章:

ios - 如何从连续的 URL 中获取数据

ios - 汉堡菜单/侧菜单外观错误

SQL 连接 : selecting the last records in a one-to-many relationship

MongoDB查找性能: single compound index VS two single field indexes

c++ - 在 C++ 中检查我的删除函数的范围

python - 使用 Python 获取当月的所有日期

带有两个拇指的 Android Seekbar

ios - UITableView 自定义单元格不工作

Swift 泛型从数组中删除类实例

Excel:在列中搜索指定值,返回同一行不同列中的值