Question
Is it possible to access a specific element in a value pack? Similarly to an array subscript (random access)?
Background
I want to construct a chain
method accepting multiple sequences with the same element type.
let sequence = chain(1...5, [6, 7, 8], CollectionOfOne(9))
For this to work I need two things:
- Same-element requirement (currently being work by @simanerush).
- Pack iteration (already implemented in Swift 6.0).
Once those two features are released, we could write the function as:
func chain<E, S>(_ sequence: repeat each S, element: E.Type = E.self) -> ChainedSequence<E, repeat each S> where repeat each S: Sequence<E> {
ChainedSequence(repeat each sequence)
}
However, I am having troubles implementing the IteratorProtocol
in an "efficient manner".
struct ChainedSequence<E, each S>: Sequence<E> where repeat each S: Sequence<E> {
let sequences: (repeat each S)
func makeIterator() -> some IteratorProtocol<E> {
ChainedIterator(sequences)
}
struct ChainedIterator: IteratorProtocol<E> {
let sequences: (repeat each S)
var iterator: (any IteratorProtocol<E>)?
init(_ sequence: (repeat each S)) {
self.sequences = sequences
self.iterator = // Retrieve the first iterator (or nil)
}
mutating func next() -> E? {
guard var iterator else {
return nil
}
if let element = iterator.next() {
self.iterator = iterator
return element
}
guard var iterator = /* Retrieve the next sequence and makeIterator() */ else {
return nil
}
let element = iterator.next() // I need to check element is not nil, but I simplified for demo purposes
self.iterator = iterator
return element
}
}
}
In the next
function, I could iterate through the sequences with the pack iteration for
-in
but that would be inefficient since I would have to start iterator from the first element of the value pack.