Daily iOS
Swift

Generics and type erasure

You have an Iterator protocol with getNext() and hasNext(), and you want to change it from Int-only to generic with associatedtype Element. After the change, building an [Iterator] array no longer compiles. Why?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A protocol with an associated type isn't a complete type until Element is filled in, so it can't be an array's element type directly, and even boxed as any Iterator the members that use Element are restricted.

Share a question