【问题标题】:Swift - passing parameter from non-generic function to a generic oneSwift - 将参数从非泛型函数传递到泛型函数
【发布时间】: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 的类型,你需要openViewControllerT 是一个具体类型(这就是它起作用的原因与FFF)。使其与 Module 一起使用的一种可能方法是构建类型擦除,例如 Rob 对链接问答的回答中所示。

标签: ios swift generics swift3


【解决方案1】:

确实,正如 cmets 中所建议的,潜在问题是协议不符合协议。不过,错误消息令人难以置信的误导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多