Why can't my Swift protocol extension port an existing function of the same type?

I am trying to create a “safe” signature operator for a collection — one that ignores parts of ranges that go beyond the available indexes for the collection.

The desired behavior is to return Slice in all cases; when there is no overlap between the index range and the collection range, and an empty array should be returned.

This seemed like a direct extension of the technique presented in this answer . The documentation for the collection index operator is very simple :

subscript(bounds: Range<Self.Index>) -> Slice<Self> { get }

But when I apply the same types in my wrapper, I get the following: snippet

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]
    }
}

? , Range<Self.Index> ( ), ?

+4
1

Collection SubSequence ( ):

subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get }

, :

subscript(bounds: Range<Self.Index>) -> Slice<Self> { get }

- , SubSequence Slice<Self>. , Collection, - - SubSequence Slice<Self>.

, , SubSequence :

extension Collection {
    subscript(safe bounds: Range<Index>) -> SubSequence {

        // as the method returns a SubSequence,
        // use the regular subscript to get an empty SubSequence
        let empty = self[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]
    }
}
+4

Source: https://habr.com/ru/post/1663254/


All Articles