Concrete Collection/Generator protocol and type


I would like to have various kinds of generators and eventually their collection counterparts of a concrete type, say Card. This is an example with generators to illustrate my intention.

typealias Card = Int
typealias Predicate = Int

protocol CardGenerator: GeneratorType {
    typealias Element = Card
    // + some common functions to the protocol

class ConcreteGenerator: CardGenerator {
    typealias Element = Card

    // some complex element fetching, some implicit filtering and transforms are here
    func next() -> Element? { return nil }

class FilteredGenerator: CardGenerator {
    typealias Element = Card
    let predicate: Predicate

    init(predicate: Predicate) {
        self.predicate = predicate

    // some complex element fetching, multiple filters and transforms are here
    func next() -> Element? { return nil }

func select(predicate:Predicate?) → CardGenerator {
    if predicate != nil {
        return FilteredGenerator(predicate:predicate!)
    else {
        return ConcreteGenerator()

I am getting:

"error: protocol 'CardGenerator' can only be used as a generic constraint because it has Self or associated type requirements”

How can I have a non-generic collection or generator protocol with specific element type tied to the protocol?



Could you please specify the protocol GeneratorType? Your CardGenerator conforms to it, but there is no definition. The code works for me when I remove the conformance, so more information on the GeneratorType is needed.

1 Like

(Damn, a necrobump of a thread only a week older than the mailing list :flushed:)

GeneratorType is called IteratorProtocol nowadays (from Swift 3 onward, I think).