2017-11-12 6 views
2

私のアプリはAppBaseController(ログイン後に提示)を動的に変更できます。それは、次の上に置くことができ :以下を返す一般的な方法:UIViewController、UINavigationController、UITabController

メニューコントローラ(タイプのUIViewController)、UINavigationController、またはUITabBarController

私は工場でこのコントローラを作成していて、見えプロトコルに準拠するために工場をしたいと思います確認工場のの

protocol MainRootApplication { 
    func create() -> UIViewController 
} 

2例:(依存性の注入のためのAutoInject Swinjectを使用)

class MenuControllerFactory: Factory,MainRootApplication { 
    func create() -> MenuController { 
     self.container.autoregister(MenuController.self, initializer: MenuController.init) 
     return self.container.resolve(MenuController.self)! 
    } 
} 

class MainTabBarControllerFactory: Factory, MainRootApplication { 
    func create() -> MainTabBarController { 
     self.container.autoregister(MainTabBarController.self, initializer: MainTabBarController.init) 
     return self.container.resolve(MainTabBarController.self)! 
    } 
} 
このような

"MainTabBarController"のタイプがUIViewControllerではないため、これは達成できません。

強制的にキャスティングすることなくこれを行うにはどうしますか?

答えて

1

おそらく関連する種類を使用しますか?

protocol MainRootApplication { 
    associatedtype ControllerType: UIViewController 
    func create() -> ControllerType 
} 

そして、あなたの工場は次のようになります:

class MenuControllerFactory: Factory,MainRootApplication { 
    typealias ControllerType = MenuController 
    func create() -> MenuController { 
     self.container.autoregister(MenuController.self, initializer: MenuController.init) 
     return self.container.resolve(MenuController.self)! 
    } 
} 

class MainTabBarControllerFactory: Factory, MainRootApplication { 
    typealias ControllerType = MainTabBarController 
    func create() -> MainTabBarController { 
     self.container.autoregister(MainTabBarController.self, initializer: MainTabBarController.init) 
     return self.container.resolve(MainTabBarController.self)! 
    } 
} 
+0

@Seeperすごい感謝!これはそれを行うのようなクールな方法です!ちょうど最後の質問でしょう、これはどのように可能ですか?これは実際にはキャストされていますが、キャストなしでは、なぜコンパイラはこれを承認しますか? – MCMatan

+0

@MCMatanどのように動作するのか、ジェネリックタイプのプロトコルよりも優れている理由を知るために、関連するタイプをすばやく調べるだけです。 – Sweeper

関連する問題