Swift泛型类型的属性和方法 [英] Swift generic type property and method
问题描述
我如何在属性中存储泛型类型,然后使用该类型属性传递方法?
How do I store generic type in property and then use that type property to pass in method?
我有一个工厂,其方法接收视图控制器类型但返回的实例
I have factory whose method receives view controllers type but returns instance of that view controller (container takes care of that).
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 }
现在,我想执行以下操作:
Now I would like to do something like:
factory.getViewController(self.destinationViewController)
我在其中声明 destinationViewController
作为 LoginViewController.self
但它不能那样工作。奇怪的是,如果我直接执行此操作,它将起作用:
But its not working like that. Weird thing is that it is working if I do it directly:
factory.getViewController(LoginViewController.self)
有帮助吗??谢谢
推荐答案
没有看到解决的代码,就不可能说为什么会崩溃,但是我有个好主意。我怀疑您误解了通用类型参数和运行时类型参数之间的区别。请考虑以下简化代码。
Without seeing the code for resolve
it's not possible to say why it's crashing, but I have a good idea. I suspect you're mistaking the difference between generic type parameters and runtime type parameters. Consider this simplified code.
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 !!!!!!
为什么最后一种情况是Super / Sub?因为 printType< T>
在编译时已解决。它只看定义:
Why is the last case Super/Sub? Because printType<T>
is resolved at compile time. It looks just at the definitions:
func printType<T>(type: T.Type)
let type: Super.Type
printType(type)
要完成这项工作,我需要 T
,这样 T.Type
与 Super.Type $相同c $ c>。好吧,这就是
超级
。因此,将其编译为:
To make this work, I need a T
such that T.Type
is the same as Super.Type
. Well, that's Super
. So this gets compiled as:
printType<Super>(type)
现在在运行时,我们看到 type
等于 Sub.self
,它是 Super.type
的子类型,所以可以。我们将其传递给 printType< Super>
并获得您所看到的响应。
Now at runtime, we see that type
is equal to Sub.self
, which is a subtype of Super.type
, so that's ok. We pass it along to printType<Super>
and get the response you're seeing.
解决
,您在要使用 type $ c的某个地方使用
T
$ c>,而您正在尝试解析 UIViewController
,它可能返回nil。
So probably internal to resolve
, you're using T
somewhere that you wanted to use type
, and that you're trying to "resolve" UIViewController
, which probably returns nil.
这篇关于Swift泛型类型的属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!