【发布时间】:2019-10-11 22:16:48
【问题描述】:
为什么我无法在下面的代码中分配和读取 Type B 的值? B.self 应该作为类型而不是实例传递,所以它应该访问 class B 中的静态变量对吗?
class A{
}
class B:A{
static var a = 5
}
class c{
static func a(){
b(type: B.self)
}
static func b(type:B.Type){
print(type.a)
}
func takeObject<T>(type:T.Type){
print(type(of:String.self)) // String.Type
print(type) // B
print(type.a) // Value of type 'T' has no member 'a'
var a :type // Use of undeclared type 'type'
}
}
let objects : c = c()
objects.takeObject(object: B.self)
请纠正我,我是这个话题的新手,看起来很有趣。
【问题讨论】:
-
很难说出你在问什么。首先,
a在takeObjects()函数中做了什么?您要分配什么类型?为什么要打印String.Type的值?你为什么要这样做?我唯一可以帮助您的是takeObjects()函数的第 3 行。做print((type as! B).a)。这会将泛型类型转换为特定类型B。此外,将函数参数type重命名为其他名称,以避免与函数type(of:)发生冲突。抱歉,我只能用当前问题的措辞来做这些了。 -
@AlexH 对不起代码措辞,我想将自定义类型作为函数参数传递,然后使用它们。
-
你想用它们做什么? @Tushar Sharma
-
您会制作有限数量的可以跟踪的对象吗?
-
@AlexH 是 4 或 5。