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?