How to refer to nested generic parent type from nested type in extension

It is possible to refer to a nested generic parent type by its bare name if the nested type is placed in the original declaration:

extension Namespace {
    struct Parent<T> {
        struct Child {
            var parent: Parent
        }
    }
}

However this is not possible when written in an extension:

extension Namespace.Parent {
    struct Child {
        var parent1: Parent // Cannot find type 'Parent' in scope
        var parent2: Namespace.Parent // Reference to generic type 'Namespace.Parent' requires arguments in <...>
    }
}

I'm guessing the case of parent1 is a bug and it should be possible to write? Does anyone know any workarounds without introducing a duplicate generic parameter on Child?

T is in scope regardless, it’s only the shorthand Parent that doesn’t work. (That shorthand is regarded as a mild mistake, since it gets in the way of writing Parent<U> sometimes.)

2 Likes

True. That's not quite what I need in my case though. Let me rephrase the question. Both Parent and Child refine separate protocol that have an associated type that shares the same name (Pair in this case). I want Child to use whatever type Parent is using, so I want to write it as a typealias of Parent.Pair. That's where I run into problems, because both associated type requirements have the same name, I'd have to write typealias Pair = Pair.

extension Namespace {
    struct Parent<A, B> {
        typealias Pair = (A, B)
    }
}

extension Namespace.Parent {
    struct Child {
        // How do I refer to Parent.Pair here?
        typealias Pair = Pair // Type alias 'Pair' references itself
        typealias Pair = Parent.Pair // Cannot find type 'Parent' in scope
    }
}

Ah I got it now – I can just write typealias Pair = Namespace.Parent<A, B>.Pair because like you mentioned A and B are still in scope. Thanks!

2 Likes