2

This answer suggests how to extend the String class to enable subscripting. I thought it could be reused across my app by extending the Collection protocol instead. But this bit:

// https://stackoverflow.com/a/46634511
extension Collection {
    subscript(value: Int) -> Self.SubSequence {
            self[index(at: value)]
    }

    private func index(at offset: Int) -> Self.Index {
            index(startIndex, offsetBy: offset)
    }
}

cannot be compiled, because:

test.swift:3:7: error: cannot subscript a value of type 'Self' with an argument of type 'Self.Index'
                self[index(at: value)]
                    ^
test.swift:3:7: note: overloads for 'subscript' exist with these partially matching parameter lists: ((UnboundedRange_) -> ()), (Int), (Range<Self.Index>)
                self[index(at: value)]
                    ^

According to the docs, Collection already lets you subscript by index, but clearly the compiler doesn't recognize it.

What is going on here?

amyspark
  • 520
  • 1
  • 4
  • 15

1 Answers1

1

You have used the wrong return type for the subscript. It should be Self.Element, not Self.SubSequence:

subscript(value: Int) -> Self.Element {
    self[index(at: value)]
}

Presuambly, the compiler finds that there is a subscript that returns a Self.SubSequence (the return type apparently takes priority in overload resolution here), and notices that it doesn't accept a Self.Index, hence the error.

A more helpful compiler would probably output an error message like "cannot convert return expression of type Self.Element to return type Self.SubSequence".

Sweeper
  • 213,210
  • 22
  • 193
  • 313