[swift-users] AnySequence and type erasure

Dmitri Gribenko gribozavr at gmail.com
Fri Jun 17 08:49:18 CDT 2016


On Fri, Jun 17, 2016 at 1:39 AM, Svein Halvor Halvorsen via
swift-users <swift-users at swift.org> wrote:
> 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?:

Hi,

Your design should work, but it won't provide optimal performance.
Sequence has a lot of requirements that can be customized by the
conforming type (e.g., map()).  We need to forward those to the
original type to get the best performance.

While you can create a closure for each of the forwarded methods,
let's say n in total, it is n times more wasteful compared to using
just a single reference like the standard library does.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-users mailing list