Confused by MutableCollection and RangeReplaceableCollection's subscript(_:)

  1. Doesn't subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get set } means MutableCollection could change length?
  2. Why does RangeReplaceableCollection.subscript(_:) only support get while set could easily be implemented with replaceSubrange(_:with:)?

Yes. The default implementation for MutableCollection should trap if the replaced slice length doesn't match (code here).

Obviously this is not as good as ensuring it through the type system, but it's better than nothing and facilitates e.g.

unsafemutablebuffer[2..<12].sort(by: >)

Because subscript access strongly implies a constant-time operation, whereas replaceSubrange(_:with:) is linear complexity.


But isn't MutableCollection.subscript(bounds: Range<Self.Index>) linear? Why is it OK there but not in RangeReplaceableCollection?

I think the distinction here is "linear in the size of the slice" vs. "linear in the size of the full collection", but you're right, it's not as obvious as "linear vs. constant" once you're talking about slices. Maybe we could say "subscripts should be linear in the size of the index"?

1 Like

Yes, that'll be more clear.