Shared copy function in Swift

I'm trying to create a generic Swift function that will take two collections and copy part of one to part of the other, sort of std::copy

in terms of semantics and memcpy

in terms of interface. However, I can't seem to find the correct arguments / arguments arguments for it to work.

The goal is to be able to call it that way, possibly by omitting any of the last three parameters:

copy(&output, input, offsetA: 0, offsetB: 4, count: 20)

      

This is what I have so far:

func copy
    <T: CollectionType, U: CollectionType where
        T.Generator.Element == U.Generator.Element,
        T.Index == Int, T.Index == U.Index,
        T.Generator.Element: Equatable>
    (inout a: T, b: U, offsetA: Int = 0, offsetB: Int = 0, count: Int? = nil) {
    let max = count ?? b.endIndex - b.startIndex - offsetB
    for i in 0..<max {
        let indA = offsetA + i
        let indB = offsetB + i
        a[indA] = b[indB]
    }
}

      

However, I have this error on the line a[indA] = b[indB]

:

Could not find an overload for "index" that takes the supplied arguments

This is somewhat surprising, since the nearly identical general constraints allow me to compare elements, which means the type must be correct at least.

What am I missing? Otherwise, is there a function to do this elsewhere?

+3


source to share


1 answer


This error is due to CollectionType

not providing an assignable index. The switch T

matches MutableCollectionType

, which adds one.

PS you can switch T.Index == Int

to T.Index: RandomAccessIndexType

if you want to make it more versatile. This can lead to misleading calculations max

.



Also I think you can drop the requirement for the elements to be equal, I don't think you are using it. But remember that this will be a shallow copy if the elements are classes.

Perhaps you should take a look at the protocol ExtensibleCollectionType

, which adds the ability to create fresh empty collections of this type and add new items to them, and RangeReplaceableCollectionType

which adds the ability to update ranges in collections with values ​​from other collections (as well as delete item ranges, insert new items, etc.) etc.).

+4


source







All Articles