Why don't we have a non-inserting element copy?

Inspired while reading a book about C++'s STL:

extension MutableCollection {

    /// Copies elements from the given collection on top of elements of this
    /// collection until one runs out.
    public mutating func copy<C: Collection>(from collection: C) -> (Index, C.Index) where C.Element == Element

    /// Copies elements from the given sequence on top of elements of the
    /// collection until one runs out.
    @inlinable
    public mutating func copy<S: Sequence>(from sequence: S) -> (Index, S.Iterator) where S.Element == Element

    /// Overlays elements from the given iterator onto the elements of the
    /// collection until one runs out.
    public mutating func copy<I: IteratorProtocol>(from iterator: inout I) -> Index where I.Element == Element

}

extension MutableCollection where Self: BidirectionalCollection {

    /// Copies elements from the given collection on top of elements of this
    /// collection, backwards, until one runs out.
    public mutating func copyBackwards<C: BidirectionalCollection>(from collection: C) -> (Index, C.Index) where C.Element == Element

}

Any reason we don't have these already? There are many similar methods for RangeReplaceableCollection, so it's odd that MutableCollection has nothing. Maybe I'll add a bug (enhancement) report....

1 Like

Kinda curious, what’s the use case of it?

When you want to replace multiple element values in a mutable collection, and the elements are consecutive. Like, reset my array to all zeros:

var myArray: [Double] = /*...*/
//...
myArray.copy(from: repeatElement(0.0, myArray.count))

I was reading about C++ STL, and noticed that not only was there the direct copy functions, some of the other functions had "copy" variants. We have equivalents to some of those other functions already, but we can't compete with the "copy" variants because we don't have a copy-primitive to compose with our equivalents. The closest we have are in RangeReplaceableCollection, but they insert new and/or replace old elements; there's no option for collections that can't change their size.