扩展 CollectionType 添加 indexOutOfRange 函数

Extend CollectionType add indexOutOfRange function

我正在尝试添加一个函数,告诉我索引是否超出数组范围。

CollectionType 的startIndex 和endIndex 好像是通用的,所以我试图限制仅在索引类型为Int 时扩展。 此代码无法编译:

extension CollectionType where Index.Type is Int {
    public func psoIndexOutOfRange(index: Index.Type) -> Bool{
        return index < self.startIndex || index > self.endIndex
    }
}

可能吗?添加这个的正确方法是什么。

怎么样:

extension CollectionType where Index: Comparable {
    public func psoIndexOutOfRange(index: Index) -> Bool{
        return index < self.startIndex || index >= self.endIndex
    }
}

正如@MartinR 所建议的,如果您使用 Comparable 而不是将 Index 限制为 Int.

类型,则更通用

我个人认为这作为 Range 的扩展会更好,而不是 CollectionType:

extension Range where T: Comparable {
    func contains(element: Generator.Element) -> Bool {
        return element >= startIndex && element < endIndex
    }
}

你可以这样称呼它(indices returns 从集合的开始到结束索引的范围):

[1,2,3].indices.contains(2)

注意,CollectionTypeRange 符合)已经有一个 contains 方法——但通过线性搜索完成。这会重载 contains 范围,专门在恒定时间内执行此操作。

此外,如果您这样做是为了将其与下标提取结合起来,请考虑添加一个可选的提取以简化操作:

extension CollectionType where Index: Comparable {
    subscript(safe idx: Index) -> Generator.Element? {
        guard indices.contains(idx) else { return nil }
        return self[idx]
    }
}

let a = [1,2,3]
a[safe: 4]  // nil