今回は短い内容になりますが、SwinjectStoryboard
と通常の Storyboard
で UIViewController
を生成する方法を紹介したいと思います👷♀️
SwinjectStoryboard
については下記を参照してください。ちなみに現時点でリリースされている最新版のソースをビルドすると SwinjectStoryboardOption
の不備によりコンパイルエラーが発生するので、master
をビルドすることをおすすめします👀
結論
UIViewController
の Extension
クラスメソッドとして下記のように定義しました。これにより、Inject
が必要な UIViewController
に限らずインスタンスを生成できます。
extension UIViewController { enum StoryboardType { case normal case swinject(container: Container) } class func create<T>(_ sbName: String, identifier: String? = nil, type: StoryboardType = .normal) -> T where T: UIViewController { switch type { case .normal: let sb = UIStoryboard(name: sbName, bundle: nil) let vc: T if let identifier = identifier { vc = sb.instantiateViewController(identifier: identifier) as! T } else { vc = sb.instantiateInitialViewController() as! T } return vc case .swinject(let container): let sb = SwinjectStoryboard.create(name: sbName, bundle: nil, container: container) let vc: T if let identifier = identifier { vc = sb.instantiateViewController(withIdentifier: identifier) as! T } else { vc = sb.instantiateInitialViewController() as! T } return vc } } }
使い方はこんな感じ
let container = Container() // TODO: Register Dependencies. let hogeViewContoller = HogeViewController.create(HogeViewController.className, type: .swinject(container: container))
てな感じで本日も以上になります🍺