从字符串创建类类型,作为具体类型传递给泛型参数Swift
我有从字符串创建类类型,作为具体类型传递给泛型参数Swift,swift,generics,swift-protocols,Swift,Generics,Swift Protocols,我有protocolp,class A和B,我的目标是使用从字符串创建的class-Type参数调用泛型方法A(:T.Type) protocol P: class { static var p: String { get } } extension P { static var p: String { return String(describing: self) } } class A: P { func a<T: P>(_: T.Type) {
protocolp
,class A和B
,我的目标是使用从字符串创建的class-Type参数调用泛型方法A(:T.Type)
protocol P: class {
static var p: String { get }
}
extension P {
static var p: String { return String(describing: self) }
}
class A: P {
func a<T: P>(_: T.Type) {
print(T.p)
}
}
class B: P {}
但是如果假设我们有一个类名数组,而不知道它们的具体类型,那么我们如何传递它们呢
["ClassA", "ClassB", "ClassC"].forEach({ className in
let type = NSClassFromString(className) as! ????
A().a(type)
})
在Swift中,泛型声明中的类型参数需要在编译时求解 因此,您的
?
需要是符合p
的具体类型。但是您不能使用您描述的任何具体类型A.Type
或B.Type
您可能知道不能使用p.Type
,因为协议p
在Swift中不符合p
本身
将方法
a(:)
声明为非泛型如何
class A: P {
func a(_ type: P.Type) {
print(type.p)
}
}
["ModuleName.A", "ModuleName.B"].forEach({ className in
let type = NSClassFromString(className) as! P.Type
A().a(type)
})
您可以将类型为
p.type
的类对象传递给类型为p.type
的参数。您是否研究了SwiftKeyPath
?请参阅:@user1046037要定义密钥路径,我们不需要根类型吗?同样的事情我们需要知道。
class A: P {
func a(_ type: P.Type) {
print(type.p)
}
}
["ModuleName.A", "ModuleName.B"].forEach({ className in
let type = NSClassFromString(className) as! P.Type
A().a(type)
})