Swift generic type property and method

How to save a generic type in a property and then use the type property to pass in the method?

I have a factory whose method gets the type of view controllers, but returns an instance of this view controller (the container will take care of this).

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)! } 

}

And I have a property like this

 var destinationViewController: UIViewController.Type { get } 

Now I would like to do something like:

 factory.getViewController(self.destinationViewController) 

where I declare destinationViewController as LoginViewController.self

But it does not work like that. It is strange that it works if I do it directly:

 factory.getViewController(LoginViewController.self) 

Any help ?? Thanks

+2
source share
1 answer

Without seeing the code for resolve , it's impossible to say why it crashes, but I have a good idea. I suspect that you are mistaken in the difference between 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 !!!!!! 

Why the last case of Super / Sub? Because printType<T> allowed at compile time. It looks only on definitions:

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

To do this, I need a T such that T.Type matches Super.Type . Well, this is Super . Thus, it compiles as:

 printType<Super>(type) 

Now at runtime, we see that type is equal to Sub.self , which is a subtype of Super.Type , so ok. We pass it to printType<Super> and get the answer you see.

Thus, perhaps internally for resolve , you use T somewhere that you wanted to use type , and that you are trying to "resolve" the UIViewController , which probably returns zero.

+2
source

Source: https://habr.com/ru/post/1013519/


All Articles