Fast downcasting variables and protocols

I have a quick protocol containing one property:

protocol WireframeProtocol: class { var rootViewController: UIViewController { get } } 

Then I have a class that implements this protocol as such:

 class MenuWireframe : WireframeProtocol { let rootViewController: UIViewController init() { self.rootViewController = MenuViewController(nibName: "MenuViewController", bundle: nil) (self.rootViewController as! MenuViewController).presenter = MenuPresenter(interactor: MenuInteractor()) } } 

In my Wireframe class, the variable is actually of type MenuViewController, but should instead be declared as a UIViewController to confirm the protocol. I have to use (self.rootViewController as! MenuViewController) to downgrade it to the class I want to have access to its properties. This is good in my simple example above, but not very readable, especially in more complex situations. Is there a better way to declare a protocol variable?

Thank you very much!

+6
source share
3 answers

Yes, there is a better way, and using common protocols. To implement this, you must declare your protocol in the same way:

 protocol WireframeProtocol{ typealias RootViewController : UIViewController var rootViewController: RootViewController { get } } 

then in your adoption class set the rootViewController type as MenuViewController

 class MenuWireframe : WireframeProtocol{ let rootViewController: MenuViewController init(){ self.rootViewController = MenuViewController(nibName: "MenuViewController", bundle: nil) self.rootViewController.presenter = MenuPresenter(interactor: MenuInteractor()) } } 
+3
source

If you can change the protocol declaration, use @ zelb's answer. If you cannot, you can do something like:

 class MenuWireframe : WireframeProtocol { var rootViewController: UIViewController { return menuViewController } let menuViewController: MenuViewController! init() { menuViewController = MenuViewController(...) //... } } 
+2
source

Have you tried this:

 protocol WireframeProtocol: UIViewController { var rootViewController: UIViewController { get } } class MenuWireframe : WireframeProtocol { let rootViewController: WireframeProtocol init() { //... } } 
+1
source

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


All Articles