【发布时间】:2018-09-13 05:36:17
【问题描述】:
我正在使用 Swinject,但有一个问题困扰着我。我几乎一整天都被这个问题困住了。我怀疑这是因为 Swift 是一种静态类型语言,但我不完全确定。
我在这个操场上总结了我的问题
protocol Protocol {}
class Class: Protocol {}
let test: Protocol.Type = Class.self
func printType(confromingClassType: Protocol.Type) {
print(confromingClassType)
}
func printType<Service>(serviceType: Service.Type) {
print(serviceType)
}
print(Class.self) // "Class"
printType(serviceType: Class.self) // "Class"
print(test) // "Class"
printType(confromingClassType: test) // "Class"
printType(serviceType: test) // "note: expected an argument list of type '(serviceType: Service.Type)'"
我尝试了不同的解决方案,例如 test.self 或 type(of: test),但它们都不起作用。
所以我想我不能调用带有作为变量提供的泛型参数的函数?
【问题讨论】:
-
你到底想做什么?
-
您是否试图拥有一个接受 Class 实例作为参数的函数,换句话说,Swift 等效于 Java 的
String myFunc(Class<?> classInstance) -
您面临的问题是,使用通用占位符
T,当T是协议P,T.Type是P.Protocol(描述协议本身的元类型)和 notP.Type(描述符合P的具体类型的元类型)。您在这里要解决的具体问题是什么? -
我不确定完全理解您的意思。我的例子应该有效。我可以打电话给
printType(confromingClassType: )唯一的区别是服务类型的通用性 -
@GuillaumeL。您可以使用
test的参数调用printType(confromingClassType:),因为它有一个Protocol.Type类型的参数。printType(serviceType:)有 no such 参数。如前所述,通用占位符T的T.Type参数不能接受存在元类型(P.Type用于某些协议P)。如果是这样,您将无法说出printType(serviceType: Protocol.self),因为P.Protocol不是P.Type。再说一次,您要在这里解决的实际问题是什么?