I'm trying to come up with something that has as little overhead as possible to concatenate arbitrary sequences of similar types.
For example, I'd like to concatenate two sequences of Int
; one is an Array
the other is a Set
.
Writing the code I wish I had would look something like this:
let first = [1, 2, 3]
let second: Set = [4, 5, 6]
for el in first.concatenate(second) {
print(el) // Prints 1, 2, 3, 4, 5, 6 on each successive loop
}
Where concatenate
is the function I wish I had.
I have come up with:
extension Sequence {
func concatenate<S: Sequence>(_ sequence: S) -> AnySequence<Self.Element> where Self.Element == S.Element {
var (first, second) = (self.makeIterator(), sequence.makeIterator())
return AnySequence(AnyIterator { first.next() ?? second.next() })
}
}
My questions are:
- I would not think that this creates any extra copies of the
Array
orSet
am I right? - Are there any better suggestions (e.g., something better than
AnySequence
return, a betterwhere
clause, etc...)? - Is there something in the standard library that already covers this and I missed it?