Generics: Type "G" type restriction does not match the required Generator protocol

I am working on a Generator class that wraps another generator and provides some additional functions on top of it. I have almost everything that works, except for one thing: a convenient init that takes Sequence as a parameter and automatically creates a generator from it.

This is the code causing the error:

class MyGenerator<G: Generator>: Generator {
    typealias Element = G.Element

    var generator: G

    init (_ generator: G) {
        self.generator = generator
    }

    // ERROR: Same-type constraint type 'G' does not conform to 
    // required protocol 'Generator'
    convenience init<S: Sequence where S.GeneratorType == G>(sequence: S) {
        self.init(sequence.generate())
    }

    // [...]

    func next() -> Element? {
        return generator.next()
    }
}

What's going on here? Why doesn't Swift like my limitation? I like it.

Am I doing something wrong or is this a compiler error?

+4
source share
1 answer

, , , GeneratorOf<T> :

class MyGenerator<T>: Generator {
    typealias Element = T

    var generator: GeneratorOf<T>

    init<G: Generator where G.Element == T>(_ generator: G) {
        self.generator = GeneratorOf(generator)
    }

    convenience init<S: Sequence where S.GeneratorType.Element == T>(sequence: S) {
        self.init(sequence.generate())
    }

    // [...]

    func next() -> Element? {
        return generator.next()
    }
}
+1

Source: https://habr.com/ru/post/1547670/


All Articles