Dependency injection with storyboards. Is my code safe? :)

Hello, I am trying to transform Singleton pattern into dependency injection. Right now I feel stuck creating DI to storyboards… I am building a framework so I don’t have appDelegate and this is why I provide dependencies in my initial ViewController(I can’t use any third party DI frameworks):

 var repository : Repository
init()
{
    repository = Repository()
    super.init(nibName: nil, bundle: nil)
}

required init?(coder aDecoder: NSCoder) {
    repository = Repository()
    super.init(coder: aDecoder)
}

Then I inject those properties by adding new VC(It is created from storyboard, which is either in Bundle.main identifier of my framework.This is why I can’t use segues)

vc = UIStoryboard.init(name:"Storyboard", bundle: Bundle(identifier: "com.company.company"
            )).instantiateViewController(withIdentifier: "DocumentsSelectionViewController") as! MenuViewController
            vc!.setupDependencies(repository: self.repository)
            self.navigationController?.pushViewController(vc!, animated: true)

setupDependencies(repository: self.repository) is a simple method, which provides dependency and because it is optional in other VC I force unwrap it… How can I do it better, without force unwrapping… Is my code safe?

Use if let:

if let vc = UIStoryboard.init(...).instantiateViewController(...) as MenuViewController 
{
    vc.setupDependencies(repository: self.repository)
    self.navigationController?.pushViewController(vc, animated: true)   
}

Or use guard:

guard let vc = UIStoryboard.init(...).instantiateViewController(...) as MenuViewController 
    else { return }
vc.setupDependencies(repository: self.repository)
self.navigationController?.pushViewController(vc, animated: true)

Dependency injection is great but less productive, I try to balance those out. I’m guessing you are using forced unwrapped optionals in your view controllers, I would add a test project to check for successful vc setup.

This topic was automatically closed after 166 days. New replies are no longer allowed.