I'm sure people here know about the problem that AnySequence, AnyGenerator, etc solves. In Swift, a protocol can have an associated type, which is kinda like generics, but you cannot declare a variable like this:
let sequence: SequenceType<Int> 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. 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. Can someone please look at this code, and give me constructive feedback? Is this a novel and working solution, or am I missing something?: 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 }
_______________________________________________ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users