I'm trying to create a "safe" subscripting operator for a collection -- one that ignores portions of ranges that go outside the available indexes for the collection.
The desired behavior is to have a Slice returned in all cases; when there no overlap between the subscript range and the collection range, and empty array should be returned.
This seemed like a straightforward expansion on the technique presented in this answer. The documentation of the collection subscript operator is very straightforward:
subscript(bounds: Range<Self.Index>) -> Slice<Self> { get }
But when I adopt those same types in my wrapper function, I get the following:
Copy/paste version:
extension Collection where Indices.Iterator.Element == Index {
subscript(safe bounds: Range<Self.Index>) -> Slice<Self> {
let empty = Slice(base: self, bounds: (startIndex..<startIndex))
guard bounds.lowerBound < endIndex else { return empty }
guard bounds.upperBound >= startIndex else { return empty }
let lo = Swift.max(startIndex, bounds.lowerBound)
let hi = Swift.min(endIndex, bounds.upperBound)
return self[lo..<hi]
}
}
Why can't I subscript a Collection in this way? Why is the compiler confirming that I'm using the correct type of Range<Self.Index>
(specified in the documentation) yet still considering it an error?
` is expected. Granted, the error message (as so often) is very misleading.– matt Dec 08 '16 at 17:00