swift - 访问类实例外部的泛型类类型
问题描述
这是我的代码:
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
instance Person
in 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
. 我明白了,但是有什么解决方法吗?一直重复泛型只是感觉不对。
解决方案
运行此行后
let person = Person<Any>()
person
表示这个静态类
class Person {
func printMyType() {
print(Any.self)
}
}
在类被实例化的那一刻,T
被(固定)替换为尖括号内的类型
推荐阅读
- html - 在 Django 中,如何从 html Input 标签中提取 ID 属性,而不使用 django 表单
- cassandra - COPY FROM 数据时如何覆盖字段?
- excel - Excel 中的公式:匹配年份和日期
- java - 无法从 START_OBJECT 令牌中反序列化“java.lang.Boolean”的实例
- apache - 为什么 RewriteRule ^(.*)$ https://domain.fr/$1 [L,R=301,NC] 在新的 url 重定向中保留旧类别?
- android - React Expo 更改目标 Android API
- java - Spring ResponseBodyEmitter 未在响应中设置 Content-Type 标头
- java - 每次我进入活动时,如何使活动不重新加载/刷新?
- java - 线程“主”java.lang.NullPointerException 中的 LDAP 查询 Java 异常
- java - 调用 init 方法失败;添加 Hibernate 环境后,嵌套异常是 java.lang.NoSuchMethodError