[swift-dev] [Proposal] RangeReplaceableCollection should inherits from MutableCollection

frogcjn at 163.com frogcjn at 163.com
Tue Dec 5 04:08:11 CST 2017


Yes.  ‘replaceSubrange(myRange, with: newCharacters)’ is different than subscript, because it may change the length. 

But any subscript could do that replaceSubrange could do, right?

在 2017年12月5日,10:48,Brent Royal-Gordon <brent at architechies.com> 写道:

>> On Dec 2, 2017, at 12:31 PM, Cao, Jiannan via swift-dev <swift-dev at swift.org> wrote:
>> 
>> I'd like to discuss the relation between RangeReplaceableCollection and MutableCollection
>> 
>> MutableCollection is a Collection type that can { set } any element with subscript(position: Index). (and also { set } for subscript(range: Range<Index>))
>> 
>> RangeReplaceableCollection requires a function replaceRange(_:with:)
>> 
>> If a type conforms to RangeReplaceableCollection, it means any of its range can be replaced, that includes the situation to replace only one element.
>> So if some type conforms to RangeReplaceableCollection, it is sufficient to be a MutableCollection.
>> So I think the RangeReplaceableCollection should conforms to MutableCollection should inherits from MutableCollection.
> 
> 
> I thought this too a couple years ago, but it's not really true. `MutableCollection` requires not only that you be able to set elements, but also that when you do so, it doesn't change any of the indices in the collection. Some collections can't guarantee that. For example, `String` can't conform to `MutableCollection` because if you set some character in the middle of the string to a character that's a different size, it might move characters later in the string to different indices. So Swift lets you say `myString.replaceSubrange(myRange, with: newCharacters)`, but it doesn't let you say `myString[myRange] = newCharacters`.
> 
> `MutableCollection` and `RangeReplaceableCollection` are very similar in that they both involve changing a collection. But they are different *kinds* of changes to a collection, so it makes sense for a collection to support either one of them without supporting the other.
> 
> -- 
> Brent Royal-Gordon
> Architechies
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20171205/d9b327ed/attachment.html>


More information about the swift-dev mailing list