Being a Mutable Collection is not Sufficient to be a MutableCollection
A
MutableCollectionsupports in-place element mutation. The single new API requirement it adds toCollectionis that thesubscriptnow must also have a setter.[…]
MutableCollectionallows changing the values of a collection’s elements, but the protocolʼs documentation stipulates that the mutation must neither change the length of the collection nor the order of the elements.Setcanʼt satisfy either of these requirements.[…]
All
Dictionarywould gain from conforming toMutableCollectionand/orRangeReplaceableCollectionwould be methods that operate onIndexvalues and(Key, Value)pairs, which is probably not compelling enough to invest anything in the conformance even if it were compatible with the typeʼs implementation.
CharacterViewdoes conform toRangeReplaceableCollectionbut not toMutableCollection. Why? A string is clearly mutable; it seems logical that it should adopt this protocol. Again, we need to consider the protocolʼs semantics.[…]
However, the
Characterʼs size in the underlying storage is not the same for all characters, so replacing a singleCharactercan potentially make it necessary to move the subsequent text forward or backward in memory by a few bytes to make room for the replacement. This would make the simple subscript assignment potentially an O(n) operation, and subscripting is supposed to be O(1).[…]
The final potential issue for
CharacterViewʼs hypotheticalMutableCollectionconformance is Unicode and the complexities it brings. The existence of combining characters means that replacing a singleCharactercan actually change the stringʼs length (measured inCharacters) if the new character combines with its preceding character.
Previously: Swift 4 String Manifesto.