<div dir="ltr">I'm sure people here know about the problem that AnySequence, AnyGenerator, etc solves.<div>In Swift, a protocol can have an associated type, which is kinda like generics, but you cannot declare a variable like this:</div><div><br></div><div>let sequence: SequenceType<Int><br></div><div><br></div><div>If you want a sequence, any sequence, over ints you need to wrap the protocol in a new concrete, generic type, AnySequence<T> that itself implements the protocol SequenceType, and where the associated type Element is equal to the generic type T.</div><div><br></div><div>The standard library does this. And, like many others, I have tried to implement this for my self, to try to better understand the problem, and I expected that I would end up with a design very similar to what the standard library does. However, I have not seen the need for the complex boxing mechanism. I'm probably misunderstanding something, though.</div><div><br></div><div>Can someone please look at this code, and give me constructive feedback? Is this a novel and working solution, or am I missing something?:</div><div><br></div><div><pre style="color:rgb(0,0,0);word-wrap:break-word;white-space:pre-wrap">struct AnyGenerator<Element>: GeneratorType {
init<G: GeneratorType where G.Element == Element>(_ gen: G) {
var gen = gen
self._next = { gen.next() }
}
private let _next: () -> Element?
func next() -> Element? {
return _next()
}
}
struct AnySequence<Element>: SequenceType {
init<S: SequenceType where S.Generator.Element == Element>(_ seq: S) {
self.underestimateCount = seq.underestimateCount
self._generate = { AnyGenerator(seq.generate()) }
}
private let _generate: () -> AnyGenerator<Element>
func generate() -> AnyGenerator<Element> {
return _generate()
}
let underestimateCount: () -> Int
}</pre></div></div>