Swift 泛型类型属性和方法



如何在属性中存储泛型类型,然后使用该类型属性传入方法?

我有工厂,其方法接收视图控制器类型,但返回该视图控制器的实例(容器负责处理(。

public protocol ViewControllerFactoryProtocol {
    func getViewController<T: UIViewController>(type: T.Type) -> UIViewController
}
public class ViewControllerFactory: ViewControllerFactoryProtocol {
private let container: Container
public init(container: Container) {
    self.container = container
}
public func getViewController<T: UIViewController>(type: T.Type) -> UIViewController {
    return self.container.resolve(type)!
}

}

我有这样的财产

var destinationViewController: UIViewController.Type { get }

现在我想做这样的事情:

factory.getViewController(self.destinationViewController)

我宣布destinationViewControllerLoginViewController.self

但它不是那样工作的。奇怪的是,如果我直接这样做,它就可以工作:

factory.getViewController(LoginViewController.self)

有什么帮助吗??谢谢

如果没有看到resolve的代码,就不可能说出它为什么崩溃,但我有一个好主意。我怀疑您误解了泛型类型参数和运行时类型参数之间的区别。请考虑此简化代码。

func printType<T>(type: T.Type) {
    print("T is (T.self)")
    print("type is (type)")
}
class Super {}
class Sub: Super {}
printType(Super.self) // Super/Super. Good.
printType(Sub.self)   // Sub/Sub. Good.
let type: Super.Type = Sub.self
printType(type) // Super/Sub !!!!!!

为什么最后一个案例是超级/子?因为printType<T>是在编译时解析的。它只看定义:

func printType<T>(type: T.Type)
let type: Super.Type
printType(type)

为了完成这项工作,我需要一种T,使T.TypeSuper.Type相同。嗯,这Super.所以这被编译为:

printType<Super>(type)

现在在运行时,我们看到type等于 Sub.self ,这是 Super.type 的一个子类型,所以没关系。我们会将其传递给printType<Super>,并获得您看到的响应。

所以可能是在resolve内部,你在你想使用type的地方使用了T,并且你试图"解析"UIViewController,这可能返回 nil。

最新更新