相关疑难解决方法(0)

为什么我不能将Protocol.Type传递给通用T.Type参数?

我正在使用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)'"
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的解决方案,如test.self或type(of:test),但它们都不起作用.

所以我想我不能使用作为变量提供的泛型参数来调用函数?

generics protocols swift

17
推荐指数
1
解决办法
4607
查看次数

标签 统计

generics ×1

protocols ×1

swift ×1