首页 > 解决方案 > 访问类实例外部的泛型类类型

问题描述

这是我的代码:

class Person<T> {

    func printMyType() {
        // I have access to type T.
        print(T.self)
    }

}

class Child {
    let person = Person<Any>()

    func printPersonType() {
        // Where did type T went to? It doesn't compile.
        print(person.T.self)
    }
}

我想知道为什么我无法再访问Tinstance Personin instance的类型Child。为什么类型T消失了?为什么它在方法中可用printMyType,但不在实例之外?

以上是我的问题。下面是我想如何使用它。

我想知道是否有可能获得 的通用使用类型Person,因为现在在我的“真实”代码中,我需要重复通用约束:

class Person<T: Child> {}

class Child {}

// In this class, I want to know what Child is used.
// To accomplish this, I now need to create a type U to access Child
// Since I do not know how to access the generic type of Person.
class BirthGiver<T: Person<U>, U: Child> {
    let child: U.Type
    let person: Person<U>.Type

    init(person: T.Type, child: U.Type) {
        self.person = person
        self.child = child
    }
}

而且我需要称它为非常难看(重复代码,两次Child,可能类型不安全?):

BirthGiver(person: Person<Child>.self, child: Child.self)

我觉得这应该工作

class BirthGiver<T: Person<U>> {
    let child: Person.T
    let person: Person<U>.Type

    init(person: T.Type) {
        self.person = person
        self.child = person.U
    }
}

所以我可以这样称呼它:

BirthGiver(person: Person<Child>.self)

但这不会编译,因为没有U. 我明白了,但是有什么解决方法吗?一直重复泛型只是感觉不对。

标签: swiftgenerics

解决方案


运行此行后

let person = Person<Any>()

person表示这个静态

class Person {
    func printMyType() {

        print(Any.self)
    }
}

在类被实例化的那一刻,T被(固定)替换为尖括号内的类型


推荐阅读