Swiftgenericstypes的属性和方法
如何将genericstypes存储在属性中,然后使用该types属性传入方法?
我有工厂的方法接收视图控制器types,但返回该视图控制器的实例(容器照顾)。
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)
在那里我声明destinationViewController
为LoginViewController.self
但它不是这样工作的。 奇怪的是,如果我直接这样做,它正在工作:
factory.getViewController(LoginViewController.self)
任何帮助? 谢谢
没有看到resolve
的代码,不可能说出它为什么崩溃,但我有一个好主意。 我怀疑你误解了genericstypes参数和运行时types参数之间的区别。 考虑这个简化的代码。
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>
在编译时被parsing。 它看起来只是定义:
func printType<T>(type: T.Type) let type: Super.Type printType(type)
为了使这个工作,我需要一个T
,使Super.Type
与Super.Type
相同。 那么,这是Super
。 所以这被编译为:
printType<Super>(type)
现在在运行时,我们看到这个type
等于Sub.self
,它是Super.type
的子types,所以没关系。 我们把它传递给printType<Super>
并得到你所看到的响应。
所以可能内部resolve
,你正在使用T
地方,你想使用的type
,并试图“解决” UIViewController
,这可能返回零。