我正在尝试添加一个函数,告诉我索引是否超出数组范围。
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
}
}
这可能吗?以及添加它的正确方法是什么。
最佳答案
我个人认为这作为 Range
的扩展会更好,而不是 CollectionType
:
extension Range where T: Comparable {
func contains(element: Generator.Element) -> Bool {
return element >= startIndex && element < endIndex
}
}
您可以这样调用(indices
返回从集合的开始到结束索引的范围):
[1,2,3].indices.contains(2)
请注意,CollectionType
(Range
符合)已经有一个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
关于swift - 扩展 CollectionType 添加 indexOutOfRange 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167189/