[swift-users] AnySequence and type erasure

Svein Halvor Halvorsen svein.h at lvor.halvorsen.cc
Fri Jun 17 03:39:57 CDT 2016


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
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160617/3f77fa12/attachment.html>


More information about the swift-users mailing list