在类实例外部访问通用类类型

时间:2019-02-16 15:45:56

标签: swift generics

这是我的代码:

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)
    }
}

我想知道为什么我再也无法在实例T中访问实例Person的类型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这样的类型。我了解这一点,但是有什么解决方法吗?一直重复仿制药感觉不对。

1 个答案:

答案 0 :(得分:0)

运行此行之后

let person = Person<Any>()

person代表此静态

class Person {
    func printMyType() {

        print(Any.self)
    }
}

目前实例化的类T被(固定)替换为尖括号中的类型

相关问题