iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Swift】SwinjectStoryboard を便利に使う

今回は短い内容になりますが、SwinjectStoryboard と通常の StoryboardUIViewController を生成する方法を紹介したいと思います👷‍♀️

SwinjectStoryboard については下記を参照してください。ちなみに現時点でリリースされている最新版のソースをビルドすると SwinjectStoryboardOption の不備によりコンパイルエラーが発生するので、master をビルドすることをおすすめします👀

github.com

結論

UIViewControllerExtension クラスメソッドとして下記のように定義しました。これにより、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))

てな感じで本日も以上になります🍺

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com