【发布时间】:2016-11-07 11:29:28
【问题描述】:
这是我的游乐场,我很想使用 openInitial111() 函数,但它无法编译,openInitial222() 工作正常,有什么问题?
protocol Module : Screen {
init()
}
extension Module {
static func entity() -> Self {
return Self()
}
}
protocol Screen {
}
class FFF: Module {
required init() {
}
}
class ZZZ: NSObject {
func openInitial111(initialModule: Module.Type) {
self.openViewController(itemWithScreenStyle: initialModule.entity()) // Error : Cannot invoke openViewController
//with an argument list of type '(initWithScreenStyle:Module)
}
func openInitial222(initialModule: Module.Type) {
let f = FFF.self // FFF.Type
self.openViewController(itemWithScreenStyle: f.entity()) // works
}
func openViewController<T: Screen>(itemWithScreenStyle: T) {
print("generics")
}
}
【问题讨论】:
-
Protocols don't conform to themselves in Swift - 因此你不能使用
Module作为符合Screen的类型,你需要openViewController的T是一个具体类型(这就是它起作用的原因与FFF)。使其与Module一起使用的一种可能方法是构建类型擦除,例如 Rob 对链接问答的回答中所示。