Dependency Injection with Storyboards on Apple Platforms
Published on
Every iOS developer has written a line of code like this one at least once:
class DollInfoViewController: UIViewController {
var dollModel: Doll?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Or in the worst case, you may have seen code like this:
var dollModel: Doll!
Then, when you want to create a view controller of that type you’d do:
// First we need to check if we can actually instantiate the view controller.
guard let dollInfoVc = storyboard?.instantiateViewController(withIdentifier: "DollInfo") as? DollInfoViewController else {
fatalError("Unable to load view controller.")
}
// Then we pass in the data we want to work with.
dollInfoVc.dollModel = doll
Code like this is very error prone. The worst part is that up untul iOS 13, it was pretty much necessary to pass data around from view controller to view controller. It’s not possible to do this in any different way in different iOS versions.